//
//  YWDBTool.m
//  maintain
//
//  Created by 郑想 on 15/10/10.
//  Copyright (c) 2015年 ewin. All rights reserved.
//

#import "NSDate+Additions.h"
#import "YWApartment.h"
#import "YWAttendanceRecord.h"
#import "YWBuilding.h"
#import "YWBuildingJson.h"
#import "YWCommonTool.h"
#import "YWCompany.h"
#import "YWDBTool.h"
#import "YWDepartment.h"
#import "YWDictEquipmentRule.h"
#import "YWEquipmentType.h"
#import "YWDictMaintenanceType.h"
#import "YWEquipment.h"
#import "YWEquipmentFieldRecord.h"
#import "YWEquipmentRuleRel.h"
#import "YWEquipmentTroubleRecord.h"
#import "YWFloor.h"
#import "YWHandler.h"
#import "YWInformationBankModel.h"
#import "YWInspectionMissionModel.h"
#import "YWKeepWatchMission.h"
#import "YWLastMaintenanceTime.h"
#import "YWLocation.h"
#import "YWLoginTool.h"
#import "YWMacro.h"
#import "YWMaintanceRecordViewModel.h"
#import "YWManufacturer.h"
#import "YWMessage.h"
#import "YWMessageListViewModel.h"
#import "YWMissionRuleResult.h"
#import "YWPatrolPicture.h"
#import "YWPatrolPointRecord.h"
#import "YWPicture.h"
#import "YWQrcodeInfo.h"
#import "YWThisMonthReadingMeterCount.h"
#import "YWInspectionMissionManager.h"

#import "YWReply.h"

#import "YWLocationRecordsViewModel.h"

#import "YWWorkReminderDBManager.h"
#import "YWCirculationDBManager.h"
#import "YWInspectionMissionDBManager.h"
#import "YWReplyDBManager.h"
#import "YWKeepWatchDBManager.h"
#import "YWMaterialDBManager.h"
#import "YWEwinDBManager.h"
#import "YWAssetCheckDBManager.h"
#import "YWNoticeDBManager.h"
#import "YWTempMissionDBManager.h"
#import "YWAttendanceDBManager.h"
#import "YWMeterReadingDBManager.h"
#import "YWEquipmentUseMenthod.h"
#import "YWEquipmentUseRange.h"
#import "YWOrganization.h"
#import "YWFunctionDBManager.h"
#import "YWMonitorAlarmDBManager.h"
#import "YWMissionManager.h"

#import "YWReportTroubleDBManager.h"
#import "YWTroubleMissionDBManager.h"
#import "YWTroubleMissionModel.h"

#import "YWDetectAndUpkeepDBManager.h"


@interface YWDBTool ()
//@property (nonatomic, strong) FMDatabase* fmdb;
//@property (nonatomic, strong) FMDatabaseQueue* dbQeue;
@property (nonatomic, copy) NSString* dbPath;
@end

@implementation YWDBTool

YWSingletonM(DBTool)

    - (NSString*)databasePath : (NSString*)account
{
    @synchronized(self)
    {
        NSArray* libPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        self.dbPath = [[libPaths lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite3", account]];
        return _dbPath;
    }
}

- (NSString*)dbPath
{
    return _dbPath;
}

- (BOOL)openDatabase:(NSString*)dbName
{
    _fmdb = [FMDatabase databaseWithPath:[self databasePath:dbName]];
    [self.fmdb setShouldCacheStatements:YES];
    if (!_fmdb) {
        return NO;
    }

    if (![_fmdb open]) {
        return NO;
    }
    return YES;
}

- (void)closeDatabase
{
    [self.fmdb close];
    _fmdb = nil;
}

- (void)updateDbQeue:(NSString*)dbName
{
    _dbQeue = [[FMDatabaseQueue alloc] initWithPath:[self databasePath:dbName]];
}

- (BOOL)isExistDB:(NSString*)dbName
{
    NSFileManager* fm = [[NSFileManager alloc] init];
    return [fm fileExistsAtPath:[self databasePath:dbName]];
}

#pragma mark table meta_info
- (BOOL)createMetaInfoTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS meta_info (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, value TEXT);";
    return [_fmdb executeUpdate:sql];
}

- (NSInteger)dbVersion
{
    NSString* sql = @"SELECT * FROM meta_info WHERE name='dbversion';";
    FMResultSet* set = [_fmdb executeQuery:sql];
    if ([set next]) {
        return [[set stringForColumn:@"value"] integerValue];
    }
    [_fmdb closeOpenResultSets];
    return 0;
}

- (BOOL)setDBVersion:(NSInteger)dbVersion
{
    NSString* sql = nil;
    if (1 >= dbVersion) {
        sql = @"INSERT INTO meta_info (name, value) VALUES ('dbversion', ?);";
        return [_fmdb executeUpdate:sql, [NSString stringWithFormat:@"%ld", (long)dbVersion]];
    }
    else {
        sql = @"UPDATE meta_info SET value=? WHERE name='dbversion';";
        return [_fmdb executeUpdate:sql, [NSString stringWithFormat:@"%ld", (long)dbVersion]];
    }
}

#pragma mark - public
- (void)connectDB:(NSString*)dbName
{
    @synchronized(self)
    {
        BOOL isExistDB = [self isExistDB:dbName];
        if ([self openDatabase:dbName]) {
            //创建表
            NSInteger dbVersion = isExistDB ? [self dbVersion] : 0;
            switch (dbVersion) {
                case 0:
                    //第一次，新建并初始化各表
                    [self createMetaInfoTable];
                    
                    [self createDictEquipmentTypeTable];
                    [self createDictEquipmentRuleTable];
                    [self createEquipmentRuleRelTable];
//                    [self createDictMaintenanceTypeTable];当前3.9.0版本注释的
                    [self createEquipmentTable];

                    [self createbuildingTable];
                    [self createApartmentTable];
                    [self createFloorTable];
                    [self createLocationTable];

                    [self createPictureTable];

                    [self createEquipmentDetectionRecordTable];
                    [self createEquipmentUpkeepRecordTable];
                    [self createEquipmentTroubleRecordTable];

//                    [self createMissionLocationRelTable];当前版本3.9.1注释
                    [self createHandlerTable];
//                    [self createLastMaintenanceTimeTable];当前版本3.9.0注释

                //  [self createLocationQrcodeRelTable];
                //记录版本
                    [self setDBVersion:1];
                case 1:
                    //创建巡更表
                    [[YWKeepWatchDBManager shareManager] createAllKeepWatchTables];
                    [self createPatrolPointPictureTable];
                    [[YWAttendanceDBManager shareManager] createAttendanceRecordTable];
                    [[YWMeterReadingDBManager shareManager] createMeterReadingRecordTable];
                    [[YWMeterReadingDBManager shareManager] createThisMonthReadMeterCountTable];

                    [[YWNoticeDBManager shareManager] createNoticeTable];
                    [[YWTempMissionDBManager shareManager] createTempMissionTable];

                    [self createAttachmentTable];

                    [self setDBVersion:2];
                case 2:
                    
                    [self updateColumnInDictEquipmentTypeTable];

                    [self createDictEquipmentSubSystemTypeTable];
                    [self createDictEquipmentSystemTypeTable];

                    [self setDBVersion:3];
                case 3:

                    [self createEquipmentCustomPropertyTable];
                    [self createCustomPropertyTypeTable];
                    [self createEquipmentFieldsRecordTable];
                    [self setDBVersion:4];
                case 4:
                    //版本2.0.0
                    [self updateColumnInTempMissionTable];
                    [self updateColumnInMeterReadingRecord];
                    [self setDBVersion:5];
                case 5:
                    //版本2.1.0
                    [self updateColumnInPatrollineTable];
                    [self updateColumnInPatrolLineLocationRelTable];
                    [self createDepartmentsTable];
                    [self createDepartmentsAndHandlerTable];
                    [self updateColumnHandlerTable];
                    [self setDBVersion:6];
                case 6:
                    //版本2.1.5
                    [self createInformationBankTable];
                    [self setDBVersion:7];
                case 7:
                    //版本2.2.2,版本2.2.3
                    //[self createEquipmentCustomParameterTable];
                    //[self createCustomParameterTypeTable];
                    
                    //创建巡查功能的数据库表
                    [[YWInspectionMissionDBManager shareManager] createAllInspectionTables];
                    
                    [self createMaintenanceRecordsView];
                    [self addColumnInMessageBuildingTable];
                    [self addColumnInEquipmentTable];
                    
                    [self setDBVersion:8];
                case 8:
                    //版本3.0.0
                    [self addColumnDictEquipmentTypeTable];
                    [self addColumnInmeterReadingRecordTable];
                    
                    [[YWReplyDBManager shareManager] createReplyTable];
                    
                    [YWDetectAndUpkeepDBManager createDetectAndUpkeepMissionTable];
                    //分离了报障维修，使用新的维修表
//                    [self createTroubleMissionTable];
                    [[YWCirculationDBManager shareManager] createCirculationInfoTable];
                    //workReminder表被drop掉
                    //[[YWWorkReminderDBManager shareManager] createWorkReminderTable];
                    
                    //[self createEventView];
                    [self addColumnInRuntimeOrInitParameterTable];
                    [self addColumnInEquipmentFieldsRecordTable];
                    [self createRunTimeParameterOptionTable];
                    
                    [self setDBVersion:9];
                case 9:
                    //3.1.0
                    [self createMeterPropertyIdTable];
                    
                    [self addColumnInNoticeAndTempMissionTable];
                    //recordType = 0
                    [self createMaintenanceRecordsView];
                    
                    [self setDBVersion:10];
                case 10:
                    //3.2.1
                    [self createKeepWatchAndInspectRecordsView];
                    [self addColumnInTheMeterReadingRecordTable];
                    [self addColumnInMeterPropertyTable];
                    [self addColumnInAttendanceRecordTable];
                    
                    //[self dropAndReCreateEquipmentDetectionRecordTable];
                    //[self dropAndReCreateEquipmentUpkeepRecordTable];
                    //[self dropAndReCreateEquipmentTroubleRecordTable];
                    
                    //更新巡更表字段
                    [[YWKeepWatchDBManager shareManager] dropAndReCreateKeepWatchTables];
                    
                    //更新巡查表的字段
                    [[YWInspectionMissionDBManager shareManager] dropAndReCreateInspectionTables];
                    
                    //[self dropAndReCreateNoticeTable];
                    
                    //[self dropAndReCreateMaintenanceMissionTable];
                    //[self dropAndReCreateTroubleMissionTable];
                    
                    [self createRecordAndPostTroubleRelTable];
                    [[YWMeterReadingDBManager shareManager] createNetWorkMeterReadingRecordTable];
                    
                    //[self createEventView];
                    //[[YWEventDBManager shareManager] createEventView];
                    
                    [self setDBVersion:11];
                case 11:
                    //3.3.0
                    [self addColumnInEquipmentTypeAndSubSystemTable];
                    [self addColumInReplyTable];
                    [self createWeChatPostTroubleReporterTable];
                    
                    //物料
                    [[YWMaterialDBManager shareManager] createAllMaterialTables];
                    //菜单表
                    [[YWEwinDBManager shareManager] createEwinMenuTable];
                    
                    [self setDBVersion:12];
                case 12:
                    //3.4.0 没有新建的数据表，但是在下面dropAndReCreateTablesWithDBVersion里更新了表字段
                    
                    [self setDBVersion:13];
                case 13:
                    //3.5.0
                    [self addColumInAttendanceTable];
                    //物料 新增yearMonthDay字段
                    [[YWMaterialDBManager shareManager] addColumInApplyTable];
                    [[YWMaterialDBManager shareManager] addColumInReceipientTable];
                    [[YWMaterialDBManager shareManager] addColumInReturnTable];
                    
                    [YWDetectAndUpkeepDBManager createDetectAndUpkeepMissionEquipmentTable];
                    
                    [self setDBVersion:14];
                case 14:
                    //3.6.0
                    //清点
                    [[YWAssetCheckDBManager shareManager] createAllAssetCheckTables];
                    //新增carbonCopyIds字段，放抄送人Id
                    [[YWMaterialDBManager shareManager] addColumInReceipientTable];
                    [[YWMaterialDBManager shareManager] addColumInReturnTable];
                    
                    [self addColumnInRuntimeParameterTable];
                    [self addColumnInDetectAndUpkeepRecordTable];
                    [self addColumnsInNoticeAndTempMissionTable];
                    [self addColumnInEquipmentRuleRelTable];
                    //[[YWEventDBManager shareManager] createEventView];
                    //未读数表
                    [[YWEwinDBManager shareManager] createLastReadTimeTable];
                    //设备的使用方法和范围
                    [self createEquipmentUseMenthodTable];
                    [self createEquipmentUseRangeTable];
                    
                    [self setDBVersion:15];
                case 15:
                    //3.7.0
                    //设备的初始参数
                    [self createEquipmentInitialParameterTable];
                    //各个模块总数
                    [[YWEwinDBManager shareManager] createTotalCountTable];
                    [self setDBVersion:16];
                case 16:
                    //3.8.0 and 3.8.1
                    //添加troubleMissionType,locationId,unDistributionTroubleTotal字段
                    [self addColumnsInTables];
                    [self setDBVersion:17];
                case 17:
                    //3.8.5
                    //巡更增加updateTime字段
                    [self addColumnInMyTable];
                    //功能设置
                    [[YWFunctionDBManager shareManager] createFunctionMenuTable];
                    
                    [[YWWorkReminderDBManager shareManager] createReminderTable];
                    
                    [[YWMonitorAlarmDBManager shareManager] createAllMonitorAlarmTables];

                    [self setDBVersion:18];
                case 18:
                    //3.9.0
                    //新建各种提醒的总数表
                    [[YWWorkReminderDBManager shareManager] createReminderCountTable];
                    //提醒添加operationType字段
                    [self addColumnInRemindTable];
                    [self setDBVersion:19];
                case 19:
                    //3.9.5
                    //新创建报障表
                    [[YWReportTroubleDBManager shareManager] createAllReportTroubleTable];
                    //新创建维修表
                    [[YWTroubleMissionDBManager shareManager] createTroubleMissionApiTable];
                    //新建handler和building关联表
                    [self createHandlerAndBuildingRelTable];
                    //新建组织机构表
                    [self createOrganizationTable];
                    
                    [self setDBVersion:20];
                case 20:
                    //3.9.8
                    //新建组织机构和部门的关系表
                    [self createOrganizationAndDepartmentsRelTable];
                    //报障表新增报障系统类别字段
                    [[YWReportTroubleDBManager shareManager] addColumInReportTroubleTable];
                    //检测保养记录表增加 missionCycle字段
                    [self addColumnsInTables];
                    [self setDBVersion:21];
                case 21:
                    //这次要发的版本
                    //新增物料流转信息表
                    [[YWMaterialDBManager shareManager] createAllMaterialTables];
                    //物料申请、领用、归还表新增materialRelationId字段
                    [[YWMaterialDBManager shareManager] addColumInMaterialApplyAndStockOutAndReturnBackTable];
                    //考勤新增observeIds字段
                    [[YWAttendanceDBManager shareManager] addColumInAttendanceRecord];
                    //新建工作日报表
                    [[YWWorkReminderDBManager shareManager] createDayReportTable];
                    [self setDBVersion:22];
                case 22:
                    //下个版本......(记得去掉上一个的break)
                    break;
                default:
                    break;
            }
            [self updateDbQeue:dbName];
            [self closeDatabase];
            //需要删掉一些表的字段时，grop掉表，然后重新建表
            [self dropAndReCreateTablesWithDBVersion:dbVersion];
        }
    }
}

- (void)dropAndReCreateTablesWithDBVersion:(NSInteger)DBVersion{
    switch (DBVersion) {
        case 11:
            [self dropAndReCreateEquipmentDetectionRecordTable];
            [self dropAndReCreateEquipmentUpkeepRecordTable];
            [self dropAndReCreateEquipmentTroubleRecordTable];
            
            //更新巡更表字段
            [[YWKeepWatchDBManager shareManager] dropAndReCreateKeepWatchTables];
            
            //更新巡查表的字段
            [[YWInspectionMissionDBManager shareManager] dropAndReCreateInspectionTables];
            
            [YWDetectAndUpkeepDBManager dropAndReCreateDetectAndUpkeepMissionTable];
            //分离了报障维修，使用新的维修表
//            [self dropAndReCreateTroubleMissionTable];
            
            //通知,临时任务
            [[YWTempMissionDBManager shareManager] dropAndReCreateTempMissionTable];
            [[YWNoticeDBManager shareManager] dropAndReCreateNoticeTable];
            
            //handler
            [self dropAndReCreateHandlerTable];
        case 12:
            //更新buildingId,recordSequence字段
            [[YWKeepWatchDBManager shareManager] dropAndReCreateKeepWatchTables];
            
            //更新buildingId,recordSequence字段
            [[YWInspectionMissionDBManager shareManager] dropAndReCreateInspectionTables];
        case 13:
            //更新missionCycle,type字段
            [YWDetectAndUpkeepDBManager dropAndReCreateDetectAndUpkeepMissionTable];
        case 14:
        case 15:
            [[YWKeepWatchDBManager shareManager] dropAndReCreatePatrollineRecordTable];
            [[YWInspectionMissionDBManager shareManager] dropAndReCreateInspectionlineRecordTable];
        case 16:
            //增加receiverIds,organizationNos(在15版本时该方法写在了上面的方法中，导致字段没有添加)
            [[YWNoticeDBManager shareManager] dropAndReCreateNoticeTable];
        case 17:
            //删掉了线路表里的keepWatchMissionId，在任务表里加上patrolLineId
            [[YWKeepWatchDBManager shareManager] dropAndReCreatePatrolLineTable];
        case 18:
            //删除并重建了物料所有的表
            [[YWMaterialDBManager shareManager] dropAndReCreateAllMaterialTables];
            //drop掉之前的workRemindr表
            [[YWWorkReminderDBManager shareManager] dropWorkReminderTable];
        case 19:
            //巡查路线表删除任务id，增加updateTime
            [[YWInspectionMissionDBManager shareManager] dropAndReCreateInspectionLineTable];
            //巡查任务表增加路线id
            [[YWInspectionMissionDBManager shareManager] dropAndReCreateInspectionMissionTable];
            //删除了hasMaintenanceRecord字段
            [YWDetectAndUpkeepDBManager dropAndReCreateDetectAndUpkeepMissionTable];
            
            [self dropAndReCreateBuildingTable];
            [self dropAndReCreateApartmentTable];
            [self dropAndReCreateFloorTable];
            [self dropAndReCreateLocationTable];
        case 20:
            [self dropOrganizationAndHandlerRelTable];
        case 21:
            break;
        default:
            break;
    }
}

#pragma mark - 数据库更新表字段
- (BOOL)updateColumnInDictEquipmentTypeTable
{
    __block BOOL executeResult = YES;
    //增加字段
    if (![_fmdb columnExists:@"isExternal" inTableWithName:@"dict_equipment_type"]) {
        [_fmdb executeUpdate:@"alter table dict_equipment_type add column isExternal integer;"];
    }
    if (![_fmdb columnExists:@"organizationNo" inTableWithName:@"dict_equipment_type"]) {
        [_fmdb executeUpdate:@"alter table dict_equipment_type add column organizationNo integer;"];
    }
    return executeResult;
}

- (BOOL)updateColumnInMeterReadingRecord
{
    __block BOOL executeResult = YES;
    //增加readingMonth字段
    if (![_fmdb columnExists:@"readingMonth" inTableWithName:@"meter_reading_record"]) {
        [_fmdb executeUpdate:@"alter table meter_reading_record add column readingMonth text;"];
    }
    return executeResult;
}
- (BOOL)updateColumnInTempMissionTable
{
    __block BOOL executeResult = YES;
    //增加isRead字段
    if (![_fmdb columnExists:@"isRead" inTableWithName:@"tempMission"]) {
        [_fmdb executeUpdate:@"alter table tempMission add column isRead boolean DEFAULT 0;"];
    }
    return executeResult;
}
- (BOOL)updateColumnInPatrollineTable
{
    __block BOOL executeResult = YES;
    //增加note字段
    if (![_fmdb columnExists:@"note" inTableWithName:@"patrolline"]) {
        [_fmdb executeUpdate:@"alter table patrolline add column note text;"];
    }
    return executeResult;
}
- (BOOL)updateColumnInPatrolLineLocationRelTable
{
    __block BOOL executeResult = YES;
    //增加note字段
    if (![_fmdb columnExists:@"note" inTableWithName:@"patrolline_location_rel"]) {
        [_fmdb executeUpdate:@"alter table patrolline_location_rel add column note text;"];
    }
    return executeResult;
}
- (BOOL)addColumnInMyTable
{
    __block BOOL executeResult = YES;
    //巡更线路增加updateTime字段
    if (![_fmdb columnExists:@"updateTime" inTableWithName:@"patrolline"]) {
        [_fmdb executeUpdate:@"alter table patrolline add column updateTime timestamp;"];
    }
//    //巡查线路增加updateTime字段
//    if (![_fmdb columnExists:@"updateTime" inTableWithName:@"inspectionLine"]) {
//        [_fmdb executeUpdate:@"alter table inspectionLine add column updateTime timestamp;"];
//    }
    //巡更任务增加patrolLineId字段
    if (![_fmdb columnExists:@"patrolLineId" inTableWithName:@"keepwatchmission"]) {
        [_fmdb executeUpdate:@"alter table keepwatchmission add column patrolLineId integer;"];
    }
    //上次阅读时间增加remindTime,monitorAlarmTime字段
    if (![_fmdb columnExists:@"remindTime" inTableWithName:@"ewin_lastReadTime"]) {
        [_fmdb executeUpdate:@"alter table ewin_lastReadTime add column remindTime timestamp;"];
    }
    if (![_fmdb columnExists:@"monitorAlarmTime" inTableWithName:@"ewin_lastReadTime"]) {
        [_fmdb executeUpdate:@"alter table ewin_lastReadTime add column monitorAlarmTime timestamp;"];
    }
    return executeResult;
}
- (BOOL)updateColumnHandlerTable
{
    __block BOOL executeResult = YES;
    //增加mobile字段
    if (![_fmdb columnExists:@"mobile" inTableWithName:@"handler"]) {
        [_fmdb executeUpdate:@"alter table handler add column mobile varchar(200);"];
    }
    return executeResult;
}

- (BOOL)addColumnInMessageBuildingTable
{
    __block BOOL executeResult = YES;
    //增加ruleJsonFileUpdateTime字段
    if (![_fmdb columnExists:@"ruleJsonFileUpdateTime" inTableWithName:@"building"]) {
        [_fmdb executeUpdate:@"alter table building add column ruleJsonFileUpdateTime timestamp;"];
    }
    return executeResult;
}

- (BOOL)addColumnInEquipmentTable
{
    __block BOOL executeResult = YES;
    //增加locationText字段
    if (![_fmdb columnExists:@"locationText" inTableWithName:@"equipment"]) {
        [_fmdb executeUpdate:@"alter table equipment add column locationText text;"];
    }
    if (![_fmdb columnExists:@"coordinate" inTableWithName:@"equipment"]) {
        [_fmdb executeUpdate:@"alter table equipment add column coordinate text;"];
    }
    return executeResult;
}


- (BOOL)addColumnInRuntimeOrInitParameterTable
{
    __block BOOL executeResult = YES;
    //增加createTime status字段
    if (![_fmdb columnExists:@"createTime" inTableWithName:@"dict_equipmentCustomProperty"]) {
        [_fmdb executeUpdate:@"alter table dict_equipmentCustomProperty add column createTime timestamp;"];
    }
    if (![_fmdb columnExists:@"status" inTableWithName:@"dict_equipmentCustomProperty"]) {
        [_fmdb executeUpdate:@"alter table dict_equipmentCustomProperty add column status smallint;"];
    }
    return executeResult;
}
- (BOOL)addColumnInEquipmentFieldsRecordTable
{
    __block BOOL executeResult = YES;
    //增加createTime字段
    if (![_fmdb columnExists:@"fieldTypeId" inTableWithName:@"equipmentFields_record"]) {
        [_fmdb executeUpdate:@"alter table equipmentFields_record add column fieldTypeId integer;"];
    }
    if (![_fmdb columnExists:@"optionId" inTableWithName:@"equipmentFields_record"]) {
        [_fmdb executeUpdate:@"alter table equipmentFields_record add column optionId integer;"];
    }
    if (![_fmdb columnExists:@"optionText" inTableWithName:@"equipmentFields_record"]) {
        [_fmdb executeUpdate:@"alter table equipmentFields_record add column optionText text;"];
    }
    return executeResult;
}
- (BOOL)addColumnDictEquipmentTypeTable
{
    __block BOOL executeResult = YES;
    //增加creatorId字段
    if (![_fmdb columnExists:@"updateTime" inTableWithName:@"dict_equipment_type"]) {
        [_fmdb executeUpdate:@"alter table dict_equipment_type add column updateTime timestamp;"];
    }
    if (![_fmdb columnExists:@"status" inTableWithName:@"dict_equipment_type"]) {
        [_fmdb executeUpdate:@"alter table dict_equipment_type add column status smallint;"];
    }
    return executeResult;
}
- (BOOL)addColumnInmeterReadingRecordTable
{
    __block BOOL executeResult = YES;
    //增加uniqueTag字段
    if (![_fmdb columnExists:@"uniqueTag" inTableWithName:@"meter_reading_record"]) {
        [_fmdb executeUpdate:@"alter table meter_reading_record add column uniqueTag text;"];
    }
    return executeResult;
}

- (BOOL)addColumnInNoticeAndTempMissionTable
{
    __block BOOL executeResult = YES;
    //增加workSequence字段
    if (![_fmdb columnExists:@"workSequence" inTableWithName:@"notice"]) {
        [_fmdb executeUpdate:@"alter table notice add column workSequence text;"];
    }
    if (![_fmdb columnExists:@"workSequence" inTableWithName:@"tempMission"]) {
        [_fmdb executeUpdate:@"alter table tempMission add column workSequence text;"];
    }
    return executeResult;
}

- (BOOL)addColumnInTheMeterReadingRecordTable
{
    __block BOOL executeResult = YES;
    //增加rate,usedAmount,price,payment字段
    if (![_fmdb columnExists:@"rate" inTableWithName:@"meter_reading_record"]) {
        [_fmdb executeUpdate:@"alter table meter_reading_record add column rate float;"];
    }
    if (![_fmdb columnExists:@"usedAmount" inTableWithName:@"meter_reading_record"]) {
        [_fmdb executeUpdate:@"alter table meter_reading_record add column usedAmount float;"];
    }
    if (![_fmdb columnExists:@"price" inTableWithName:@"meter_reading_record"]) {
        [_fmdb executeUpdate:@"alter table meter_reading_record add column price float;"];
    }
    if (![_fmdb columnExists:@"payment" inTableWithName:@"meter_reading_record"]) {
        [_fmdb executeUpdate:@"alter table meter_reading_record add column payment float;"];
    }
    return executeResult;
}
- (BOOL)addColumnInMeterPropertyTable
{
    __block BOOL executeResult = YES;
    //增加recordType字段
    if (![_fmdb columnExists:@"companyName" inTableWithName:@"meterProperty"]) {
        [_fmdb executeUpdate:@"alter table meterProperty add column companyName text;"];
    }
    return executeResult;
}
- (BOOL)addColumnInAttendanceRecordTable
{
    __block BOOL executeResult = YES;
    //增加type,qrcodeId,locationText字段
    if (![_fmdb columnExists:@"type" inTableWithName:@"attendance_record"]) {
        [_fmdb executeUpdate:@"alter table attendance_record add column type smallint;"];
    }
    if (![_fmdb columnExists:@"qrcodeId" inTableWithName:@"attendance_record"]) {
        [_fmdb executeUpdate:@"alter table attendance_record add column qrcodeId varchar;"];
    }
    if (![_fmdb columnExists:@"locationText" inTableWithName:@"attendance_record"]) {
        [_fmdb executeUpdate:@"alter table attendance_record add column locationText varchar;"];
    }
    return executeResult;
}
- (BOOL)addColumnInEquipmentTypeAndSubSystemTable
{
    __block BOOL executeResult = YES;
    //增加subSystemTypeId,systemTypeId字段
    if (![_fmdb columnExists:@"subSystemTypeId" inTableWithName:@"dict_equipment_type"]) {
        [_fmdb executeUpdate:@"alter table dict_equipment_type add column subSystemTypeId integer;"];
    }
    if (![_fmdb columnExists:@"systemTypeId" inTableWithName:@"dict_equipmentSubSystem_type"]) {
        [_fmdb executeUpdate:@"alter table dict_equipmentSubSystem_type add column systemTypeId integer;"];
    }
    return executeResult;
}
- (BOOL)addColumInReplyTable{
    __block BOOL executeResult = YES;
    //增加atUserId字段
    if (![_fmdb columnExists:@"atUserId" inTableWithName:@"reply"]) {
        [_fmdb executeUpdate:@"alter table reply add column atUserId integer;"];
    }
    return executeResult;

}

- (BOOL)addColumInAttendanceTable{
    __block BOOL executeResult = YES;
    //增加uploadStatus字段
    if (![_fmdb columnExists:@"uploadStatus" inTableWithName:@"attendance_record"]) {
        [_fmdb executeUpdate:@"alter table attendance_record add column uploadStatus integer;"];
    }
    //增加coordinate字段
    if (![_fmdb columnExists:@"coordinate" inTableWithName:@"attendance_record"]) {
        [_fmdb executeUpdate:@"alter table attendance_record add column coordinate varchar;"];
    }
    return executeResult;
}

- (BOOL)addColumnInRuntimeParameterTable
{
    __block BOOL executeResult = YES;
    //增加maintenanceTypeId字段
    if (![_fmdb columnExists:@"maintenanceTypeId" inTableWithName:@"dict_equipmentCustomProperty"]) {
        [_fmdb executeUpdate:@"alter table dict_equipmentCustomProperty add column maintenanceTypeId smallint;"];
    }
    return executeResult;
}
- (BOOL)addColumnInDetectAndUpkeepRecordTable
{
    __block BOOL executeResult = YES;
    //增加recordSequence字段
    if (![_fmdb columnExists:@"recordSequence" inTableWithName:@"equipment_detection_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_detection_record add column recordSequence varchar;"];
    }
    if (![_fmdb columnExists:@"recordSequence" inTableWithName:@"equipment_upkeep_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_upkeep_record add column recordSequence varchar;"];
    }
    if (![_fmdb columnExists:@"recordSequence" inTableWithName:@"equipment_trouble_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_trouble_record add column recordSequence varchar;"];
    }
    return executeResult;
}
- (BOOL)addColumnsInNoticeAndTempMissionTable
{
    __block BOOL executeResult = YES;
    //通知和临时任务增加observerIds字段
    if (![_fmdb columnExists:@"observerIds" inTableWithName:@"notice"]) {
        [_fmdb executeUpdate:@"alter table notice add column observerIds varchar;"];
    }
    if (![_fmdb columnExists:@"observerIds" inTableWithName:@"tempMission"]) {
        [_fmdb executeUpdate:@"alter table tempMission add column observerIds varchar;"];
    }
    //检测，保养，维修任务增加observerIds字段
    if (![_fmdb columnExists:@"observerIds" inTableWithName:@"mission_maintenance"]) {
        [_fmdb executeUpdate:@"alter table mission_maintenance add column observerIds varchar;"];
    }
//    if (![_fmdb columnExists:@"observerIds" inTableWithName:@"mission_trouble"]) {
//        [_fmdb executeUpdate:@"alter table mission_trouble add column observerIds varchar;"];
//    }
    //巡查，巡更任务增加observerIds字段
    if (![_fmdb columnExists:@"observerIds" inTableWithName:@"inspectionMission"]) {
        [_fmdb executeUpdate:@"alter table inspectionMission add column observerIds varchar;"];
    }
    if (![_fmdb columnExists:@"observerIds" inTableWithName:@"keepwatchmission"]) {
        [_fmdb executeUpdate:@"alter table keepwatchmission add column observerIds varchar;"];
    }
    return executeResult;
}
- (BOOL)addColumnInEquipmentRuleRelTable
{
    __block BOOL executeResult = YES;
    //增加maintenanceCycleId字段
    if (![_fmdb columnExists:@"maintenanceCycleId" inTableWithName:@"equipment_rule_rel"]) {
        [_fmdb executeUpdate:@"alter table equipment_rule_rel add column maintenanceCycleId integer;"];
    }
    return executeResult;
}
- (BOOL)addColumnsInTables
{
    __block BOOL executeResult = YES;
//    //增加troubleMissionType字段
//    if (![_fmdb columnExists:@"troubleMissionType" inTableWithName:@"mission_trouble"]) {
//        [_fmdb executeUpdate:@"alter table mission_trouble add column troubleMissionType integer;"];
//    }
    //增加locationId字段
    if (![_fmdb columnExists:@"locationId" inTableWithName:@"attendance_record"]) {
        [_fmdb executeUpdate:@"alter table attendance_record add column locationId integer;"];
    }
    //增加unDistributionTroubleTotal字段
    if (![_fmdb columnExists:@"unDistributionTroubleTotal" inTableWithName:@"ewin_totalCount"]) {
        [_fmdb executeUpdate:@"alter table ewin_totalCount add column unDistributionTroubleTotal integer;"];
    }
    //增加handlerUniqueId字段
    if (![_fmdb columnExists:@"handlerUniqueId" inTableWithName:@"equipment_detection_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_detection_record add column handlerUniqueId integer;"];
    }if (![_fmdb columnExists:@"handlerUniqueId" inTableWithName:@"equipment_upkeep_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_upkeep_record add column handlerUniqueId integer;"];
    }if (![_fmdb columnExists:@"handlerUniqueId" inTableWithName:@"equipment_trouble_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_trouble_record add column handlerUniqueId integer;"];
    }
    //增加missionCycle字段
    if (![_fmdb columnExists:@"handlerUniqueId" inTableWithName:@"equipment_detection_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_detection_record add column missionCycle smallint;"];
    }if (![_fmdb columnExists:@"handlerUniqueId" inTableWithName:@"equipment_upkeep_record"]) {
        [_fmdb executeUpdate:@"alter table equipment_upkeep_record add column missionCycle smallint;"];
    }
    return executeResult;
}
- (BOOL)addColumnInRemindTable
{
    __block BOOL executeResult = YES;
    //增加operationType字段
    if (![_fmdb columnExists:@"operationType" inTableWithName:@"reminder"]) {
        [_fmdb executeUpdate:@"alter table reminder add column operationType smallint;"];
    }
    return executeResult;
}
#pragma mark - equipment

#pragma mark - 设备类型字典表
- (BOOL)createDictEquipmentTypeTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipment_type' (subSystemTypeId integer,equipmentTypeId integer NOT NULL UNIQUE,equipmentTypeName varchar(100),isExternal integer,organizationNo integer,ownCode varchar(30),updateTime timestamp,status smallint);";
    return [_fmdb executeUpdate:sql];
}

#pragma mark - 设备子系统类型字典表
- (BOOL)createDictEquipmentSubSystemTypeTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipmentSubSystem_type' (systemTypeId integer,subSystemTypeId integer NOT NULL UNIQUE,subSystemTypeName varchar(100));";
    return [_fmdb executeUpdate:sql];
}

#pragma mark - 设备系统类型字典表
- (BOOL)createDictEquipmentSystemTypeTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipmentSystemType_type' (systemTypeId integer NOT NULL UNIQUE,systemTypeName varchar(100));";
    return [_fmdb executeUpdate:sql];
}

#pragma mark - 设备运行参数
- (BOOL)createEquipmentCustomPropertyTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipmentCustomProperty' (equipmentTypeId integer,fieldId integer NOT NULL UNIQUE,fieldName text,required integer,maxFieldValue integer,minFieldValue integer,createTime timestamp,status smallint,maintenanceTypeId smallint);";
    return [_fmdb executeUpdate:sql];
}

#pragma mark - 设备运行参数类型
- (BOOL)createCustomPropertyTypeTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipmentCustomPropertyType' (fieldId integer NOT NULL UNIQUE,fieldTypeId integer ,fieldTypeName text,fieldTypeCode text);";
    return [_fmdb executeUpdate:sql];
}
#pragma mark - 设备运行参数下拉列表对象
- (BOOL)createRunTimeParameterOptionTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipmentRunTimeParameterOption' (fieldId integer NOT NULL,fieldOptionId integer ,fieldOptionText text);";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)insertDictEquipmentTypeWithArray:(NSArray*)dictEquipmentTypes
{
    if (dictEquipmentTypes.count==0) {
        return YES;
    }
    __block NSArray* blockDictEquipmentTypes = dictEquipmentTypes;
    __block BOOL executeResult = YES;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        __block NSString* sql = nil;
        [blockDictEquipmentTypes enumerateObjectsUsingBlock:^(YWEquipmentType* _Nonnull dictEquipmentType, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'dict_equipment_type' WHERE equipmentTypeId=?;";
            FMResultSet* set = [db executeQuery:sql, @(dictEquipmentType.equipmentTypeId)];
            
            if ([set next]) {
                sql = @"UPDATE 'dict_equipment_type' SET subSystemTypeId=?,equipmentTypeName=?, isExternal=? ,organizationNo=?, ownCode=?,updateTime=?,status=? WHERE equipmentTypeId=?;";
                executeResult = [db executeUpdate:sql, @(dictEquipmentType.equipmentSubSystemType.subSystemTypeId),dictEquipmentType.equipmentTypeName, @(dictEquipmentType.isExternal), @(dictEquipmentType.organizationNo), dictEquipmentType.ownCode,@(dictEquipmentType.updateTime),@(dictEquipmentType.status),@(dictEquipmentType.equipmentTypeId)];
            }
            else {
                sql = @"INSERT INTO 'dict_equipment_type' (subSystemTypeId,equipmentTypeId,equipmentTypeName,isExternal,organizationNo,ownCode,updateTime,status) VALUES (?, ?, ?, ?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, @(dictEquipmentType.equipmentSubSystemType.subSystemTypeId),@(dictEquipmentType.equipmentTypeId), dictEquipmentType.equipmentTypeName, @(dictEquipmentType.isExternal), @(dictEquipmentType.organizationNo), dictEquipmentType.ownCode,@(dictEquipmentType.updateTime),@(dictEquipmentType.status)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
                executeResult = NO;
            };
            sql = @"DELETE FROM 'dict_equipmentSubSystem_type' WHERE subSystemTypeId=?;";
            executeResult = [db executeUpdate:sql, @(dictEquipmentType.equipmentSubSystemType.subSystemTypeId)];
            sql = @"INSERT INTO 'dict_equipmentSubSystem_type' (systemTypeId,subSystemTypeName,subSystemTypeId) VALUES (?, ?, ?);";
            __block BOOL newResult = [db executeUpdate:sql, @(dictEquipmentType.equipmentSystemType.systemTypeId),dictEquipmentType.equipmentSubSystemType.subSystemTypeName, @(dictEquipmentType.equipmentSubSystemType.subSystemTypeId)];

            sql = @"DELETE FROM 'dict_equipmentSystemType_type' WHERE systemTypeId=?;";
            executeResult = [db executeUpdate:sql, @(dictEquipmentType.equipmentSystemType.systemTypeId)];
            sql = @"INSERT INTO 'dict_equipmentSystemType_type' (systemTypeName,systemTypeId) VALUES (?, ?);";
            newResult = [db executeUpdate:sql, dictEquipmentType.equipmentSystemType.systemTypeName, @(dictEquipmentType.equipmentSystemType.systemTypeId)];
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (NSArray *)allEquipmentSystemType{
    __block NSMutableArray* equipmentSystemTypes = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipmentSystemType_type' order by systemTypeId;";
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWEquipmentSystemType* equipmentSystemType = [[YWEquipmentSystemType alloc]init];
            equipmentSystemType.systemTypeId = [set intForColumn:@"systemTypeId"];
            equipmentSystemType.systemTypeName = [set stringForColumn:@"systemTypeName"];
            if (equipmentSystemType.systemTypeId>0 && equipmentSystemType.systemTypeName.length>0) {
                [equipmentSystemTypes addObject:equipmentSystemType];
            }
        }
        [db closeOpenResultSets];
    }];
    return equipmentSystemTypes;
}

- (NSArray *)allEquipmentSubSystemType{
    __block NSMutableArray* equipmentSubSystemTypes = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipmentSubSystem_type';";
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWEquipmentSubSystemType* equipmentSubSystemType = [[YWEquipmentSubSystemType alloc]init];
            equipmentSubSystemType.subSystemTypeId = [set intForColumn:@"subSystemTypeId"];
            equipmentSubSystemType.subSystemTypeName = [set stringForColumn:@"subSystemTypeName"];
            
            sql = @"SELECT * FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?;";
            FMResultSet* newSet = [db executeQuery:sql,@(equipmentSubSystemType.subSystemTypeId)];
            NSMutableArray *tempArray = [NSMutableArray array];
            while ([newSet next]) {
                YWEquipmentType* equipmentType = [self equipmentTypeWithFMResultSet:newSet db:db];
                equipmentType.equipmentSubSystemType = equipmentSubSystemType;
                [tempArray addObject:equipmentType];
            }
            equipmentSubSystemType.equipmentTypeArray = tempArray;
            
            [equipmentSubSystemTypes addObject:equipmentSubSystemType];
        }
        [db closeOpenResultSets];
    }];
    return equipmentSubSystemTypes;
}

- (NSArray *)allEquipmentTypeWithSystemId:(NSInteger)systemTypeId{
    __block NSMutableArray* equipmentTypes = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipmentSubSystem_type' WHERE systemTypeId=?;";
        FMResultSet* set = [db executeQuery:sql,@(systemTypeId)];
        while ([set next]) {
            YWEquipmentSubSystemType *subSystem = [[YWEquipmentSubSystemType alloc] init];
            subSystem.subSystemTypeId = [set intForColumn:@"subSystemTypeId"];
            subSystem.subSystemTypeName = [set stringForColumn:@"subSystemTypeName"];
            sql = @"SELECT * FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?;";
            FMResultSet* newSet = [db executeQuery:sql,@(subSystem.subSystemTypeId)];
            NSMutableArray *tempArray = [NSMutableArray array];
            while ([newSet next]) {
                YWEquipmentType* equipmentType = [self equipmentTypeWithFMResultSet:newSet db:db];
                equipmentType.equipmentSubSystemType = subSystem;
                [tempArray addObject:equipmentType];
            }
            if (tempArray.count) {
                [equipmentTypes addObject:tempArray];
            }
        }
        [db closeOpenResultSets];
    }];
    return equipmentTypes;
}
- (YWEquipmentType*)equipmentTypeWithFMResultSet:(FMResultSet*)set db:(FMDatabase*)db
{
    YWEquipmentType* equipmentType = [[YWEquipmentType alloc] init];
    equipmentType.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
    equipmentType.equipmentTypeName = [set stringForColumn:@"equipmentTypeName"];
    NSString* sql = @"select c.* from 'dict_equipment_type' a left join 'dict_equipmentSubSystem_type' b on b.subSystemTypeId = a.subSystemTypeId left join 'dict_equipmentSystemType_type' c on c.systemTypeId = b.systemTypeId where equipmentTypeId =?";
    FMResultSet* newSet = [db executeQuery:sql, @(equipmentType.equipmentTypeId)];
    if ([newSet next]) {
        YWEquipmentSystemType* equipmentSystemType = [[YWEquipmentSystemType alloc] init];
        equipmentSystemType.systemTypeId = [newSet intForColumn:@"systemTypeId"];
        equipmentSystemType.systemTypeName = [newSet stringForColumn:@"systemTypeName"];
        equipmentType.equipmentSystemType = equipmentSystemType;
    }

    equipmentType.isExternal = [set intForColumn:@"isExternal"];
    equipmentType.ownCode = [set stringForColumn:@"ownCode"];
    equipmentType.organizationNo = [set intForColumn:@"organizationNo"];
    equipmentType.updateTime = [set longLongIntForColumn:@"updateTime"];
    equipmentType.status = [set intForColumn:@"status"];
    
    return equipmentType;
}

- (YWEquipmentSystemType*)equipmentSystemTypeWithEquipmentTypeId:(NSInteger)equipmentTypeId{
    __block YWEquipmentSystemType*equSystemType = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
//        NSString* sql = @"SELECT * FROM 'dict_equipmentSystemType_type' WHERE systemTypeId=(SELECT systemTypeId FROM 'dict_equipmentSubSystem_type' where subSystemTypeId =(SELECT subSystemTypeId FROM 'dict_equipment_type' where equipmentTypeId =?));";
        NSString * sql = @"select c.* from 'dict_equipment_type' a left join 'dict_equipmentSubSystem_type' b on b.subSystemTypeId = a.subSystemTypeId left join 'dict_equipmentSystemType_type' c on c.systemTypeId = b.systemTypeId where equipmentTypeId =?";
        FMResultSet* set = [db executeQuery:sql,@(equipmentTypeId)];
        if ([set next]) {
            YWEquipmentSystemType* equipmentSystemType = [[YWEquipmentSystemType alloc] init];
            equipmentSystemType.systemTypeId = [set intForColumn:@"systemTypeId"];
            equipmentSystemType.systemTypeName = [set stringForColumn:@"systemTypeName"];
            equSystemType = equipmentSystemType;
        }
        [db closeOpenResultSets];
    }];
    return equSystemType;
}

- (NSTimeInterval)dicEquipmentRuntimeParameterMaxCreateTime{
    __block NSTimeInterval updateTime = 0 ;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT MAX(createTime) AS MaxCreateTime FROM 'dict_equipmentCustomProperty';";
        FMResultSet* set = [db executeQuery:sql];
        if ([set next]) {
            updateTime = [set longLongIntForColumn:@"MaxCreateTime"];
        }
        [db closeOpenResultSets];
    }];
    return updateTime;
}

- (BOOL)saveRuntimeParameterWithArray:(NSArray*)runtimeParameterArray{
    if (runtimeParameterArray.count == 0) {
        return YES;
    }
    __block NSArray* blockRuntimeParameterArray = runtimeParameterArray;
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockRuntimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter* _Nonnull equipmentFields, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"DELETE FROM 'dict_equipmentCustomProperty' WHERE fieldId=?;";
            executeResult = [db executeUpdate:sql, @(equipmentFields.fieldId)];
            sql = @"INSERT INTO 'dict_equipmentCustomProperty' (equipmentTypeId,fieldId ,fieldName ,required ,maxFieldValue ,minFieldValue ,createTime,status,maintenanceTypeId) VALUES (?,?, ?,?,?,?,?,?,?);";
            executeResult = [db executeUpdate:sql, @(equipmentFields.equipmentType.equipmentTypeId), @(equipmentFields.fieldId), equipmentFields.fieldName, @(equipmentFields.required), @(equipmentFields.maxFieldValue), @(equipmentFields.minFieldValue),@(equipmentFields.createTime),@(equipmentFields.status),@(equipmentFields.maintenanceTypeId)];
            
            sql = @"DELETE FROM 'dict_equipmentCustomPropertyType' WHERE fieldId=?;";
            executeResult = [db executeUpdate:sql, @(equipmentFields.fieldId)];
            sql = @"INSERT INTO 'dict_equipmentCustomPropertyType' (fieldId,fieldTypeId ,fieldTypeName ,fieldTypeCode) VALUES (? ,?, ?,?);";
            executeResult = [db executeUpdate:sql, @(equipmentFields.fieldId), @(equipmentFields.fieldType.fieldTypeId), equipmentFields.fieldType.fieldTypeName, equipmentFields.fieldType.fieldTypeCode];
            
            
            if (equipmentFields.options.count>0) {
                __block NSString *newsql = @"DELETE FROM 'dict_equipmentRunTimeParameterOption' WHERE fieldId=?;";
                executeResult = [db executeUpdate:newsql, @(equipmentFields.fieldId)];
                [equipmentFields.options enumerateObjectsUsingBlock:^(YWEquipmentFieldOption*  _Nonnull option, NSUInteger idx, BOOL * _Nonnull stop) {
                    newsql = @"INSERT INTO 'dict_equipmentRunTimeParameterOption' (fieldId,fieldOptionId,fieldOptionText) VALUES (? ,?, ?);";
                    executeResult = [db executeUpdate:newsql, @(equipmentFields.fieldId), @(option.fieldOptionId), option.fieldOptionText];
                }];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSTimeInterval)dicEquipmentTypeMaxUpdateTime{
    __block NSTimeInterval updateTime = 0 ;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT MAX(updateTime) AS MaxUpdateTime FROM 'dict_equipment_type';";
        FMResultSet* set = [db executeQuery:sql];
        if ([set next]) {
            updateTime = [set longLongIntForColumn:@"MaxUpdateTime"];
        }
        [db closeOpenResultSets];
    }];
    return updateTime;
}

- (NSString*)equipmentTypeNameWithTypeId:(NSInteger)equipmentTypeId{
    __block NSString* typeName = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT equipmentTypeName FROM 'dict_equipment_type' WHERE equipmentTypeId = ?;";
        FMResultSet* set = [db executeQuery:sql, @(equipmentTypeId)];

        if ([set next]) {
            typeName = [set stringForColumn:@"equipmentTypeName"];
        }
        [db closeOpenResultSets];
    }];
    return typeName ?: @"未知设备类型";
}

- (NSInteger)equipmentTypeIdWithOwnCode:(NSString*)ownCode{
    __block NSInteger equipmentTypeId = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE ownCode=?";
        FMResultSet* set = [db executeQuery:sql, ownCode];
        if ([set next]) {
            equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
        }
        [db closeOpenResultSets];
    }];
    return equipmentTypeId;
}
//运行参数
- (NSArray *)equipmentFieldsWithTypeId:(NSInteger)equipmentTypeId maintenanceTypeId:(NSInteger)maintenanceTypeId{
    __block NSMutableArray* fieldsArr = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipmentCustomProperty' WHERE equipmentTypeId = ? AND maintenanceTypeId=? AND status=0;";
        FMResultSet* set = [db executeQuery:sql, @(equipmentTypeId),@(maintenanceTypeId)];
        while ([set next]) {
            YWRunTimeParameter* equipmentField = [self equipmentFieldsWithFMResultSet:set db:db];
            ;
            [fieldsArr addObject:equipmentField];
        }
        [db closeOpenResultSets];
    }];
    [fieldsArr enumerateObjectsUsingBlock:^(YWRunTimeParameter* _Nonnull equipmentField, NSUInteger idx, BOOL* _Nonnull stop) {
        equipmentField.fieldType = [self fieldTypeWithFieldId:equipmentField.fieldId];
    }];
    return fieldsArr;
}
- (YWRunTimeParameter*)equipmentFieldsWithFMResultSet:(FMResultSet*)set db:(FMDatabase*)db
{
    YWRunTimeParameter* equipmentField = [[YWRunTimeParameter alloc] init];
    equipmentField.fieldId = [set intForColumn:@"fieldId"];
    equipmentField.fieldName = [set stringForColumn:@"fieldName"];
    equipmentField.required = [set intForColumn:@"required"];
    equipmentField.maxFieldValue = [set intForColumn:@"maxFieldValue"];
    equipmentField.minFieldValue = [set intForColumn:@"minFieldValue"];
    equipmentField.createTime = [set longLongIntForColumn:@"createTime"];
    equipmentField.status = [set intForColumn:@"status"];
    equipmentField.maintenanceTypeId = [set intForColumn:@"maintenanceTypeId"];
    NSMutableArray *optionArray = nil;
    NSString *sql = @"SELECT * FROM 'dict_equipmentRunTimeParameterOption' WHERE fieldId = ?";
    set = [db executeQuery:sql, @(equipmentField.fieldId)];
    while ([set next]) {
        if (optionArray == nil) {
            optionArray = [NSMutableArray array];
        }
        YWEquipmentFieldOption* option = [[YWEquipmentFieldOption alloc] init];
        option.fieldOptionId = [set intForColumn:@"fieldOptionId"];
        option.fieldOptionText = [set stringForColumn:@"fieldOptionText"];
        [optionArray addObject:option];
    }
    if (optionArray.count) {
        equipmentField.options = optionArray;
        equipmentField.fieldOptionValue = optionArray[0];
    }
    
    return equipmentField;
}
- (YWEquipmentFieldType*)fieldTypeWithFieldId:(NSInteger)fieldId
{
    __block YWEquipmentFieldType* fieldType = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipmentCustomPropertyType' WHERE fieldId = ?;";
        FMResultSet* set = [db executeQuery:sql, @(fieldId)];
        while ([set next]) {
            fieldType = [[YWEquipmentFieldType alloc] init];
            fieldType.fieldTypeId = [set intForColumn:@"fieldTypeId"];
            fieldType.fieldTypeName = [set stringForColumn:@"fieldTypeName"];
            fieldType.fieldTypeCode = [set stringForColumn:@"fieldTypeCode"];
        }
        [db closeOpenResultSets];
    }];
    return fieldType;
}

#pragma mark - equipmentFields_record table
/**
 *  名称	设备运行参数和维保记录表 equipmentFields_record
 */
- (BOOL)createEquipmentFieldsRecordTable
{
    NSString* sql = @"CREATE TABLE 'equipmentFields_record' (uniqueTag text,maintenanceTypeId integer,fieldId integer,fieldName text,fieldValue text,fieldTypeId integer,optionId integer,optionText text);";
    return [_fmdb executeUpdate:sql];
}
- (BOOL)updateEquipmentFieldRecords:(NSArray*)equipmentFieldRecords
{
    if (equipmentFieldRecords.count == 0) {
        return YES;
    }
    __block NSArray* blockEquipmentFieldRecords = equipmentFieldRecords;
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockEquipmentFieldRecords enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord* _Nonnull equipmentFieldRecord, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'equipmentFields_record' WHERE uniqueTag=? AND fieldId=?;";
            FMResultSet* set = [db executeQuery:sql, equipmentFieldRecord.uniqueTag, @(equipmentFieldRecord.fieldId)];

            if ([set next]) {
                sql = @"UPDATE 'equipmentFields_record' SET fieldName=?,fieldValue=? ,maintenanceTypeId=?,fieldTypeId=?,optionId=?,optionText=? WHERE uniqueTag=? AND fieldId=?;";
                executeResult = [db executeUpdate:sql, equipmentFieldRecord.fieldName, equipmentFieldRecord.fieldValue, @(equipmentFieldRecord.maintenanceTypeId),@(equipmentFieldRecord.fieldTypeId),@(equipmentFieldRecord.fieldOption.fieldOptionId),equipmentFieldRecord.fieldOption.fieldOptionText, equipmentFieldRecord.uniqueTag, @(equipmentFieldRecord.fieldId)];
            }
            else {
                sql = @"INSERT INTO 'equipmentFields_record' (uniqueTag,maintenanceTypeId,fieldId,fieldName,fieldValue,fieldTypeId,optionId,optionText) VALUES (?, ? ,? ,? ,? ,? ,? ,?);";
                executeResult = [db executeUpdate:sql, equipmentFieldRecord.uniqueTag, @(equipmentFieldRecord.maintenanceTypeId), @(equipmentFieldRecord.fieldId), equipmentFieldRecord.fieldName, equipmentFieldRecord.fieldValue,@(equipmentFieldRecord.fieldTypeId),@(equipmentFieldRecord.fieldOption.fieldOptionId),equipmentFieldRecord.fieldOption.fieldOptionText];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];

        [db closeOpenResultSets];
    }];

    return executeResult;
}
- (NSArray*)equipmentFieldRecordsWithUniqueTag:(NSString*)uniqueTag maintenanceTypeId:(NSInteger)maintenanceTypeId
{
    __block NSMutableArray* fieldRecordArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipmentFields_record' WHERE uniqueTag = ? AND maintenanceTypeId = ?;";
        FMResultSet* set = [db executeQuery:sql, uniqueTag, @(maintenanceTypeId)];
        while ([set next]) {
            YWEquipmentFieldRecord* fieldRecord = [[YWEquipmentFieldRecord alloc] init];
            fieldRecord.uniqueTag = [set stringForColumn:@"uniqueTag"];
            fieldRecord.fieldId = [set intForColumn:@"fieldId"];
            fieldRecord.fieldName = [set stringForColumn:@"fieldName"];
            fieldRecord.fieldValue = [set stringForColumn:@"fieldValue"];
            fieldRecord.maintenanceTypeId = [set intForColumn:@"maintenanceTypeId"];
            fieldRecord.fieldTypeId = [set intForColumn:@"fieldTypeId"];
            YWEquipmentFieldOption *option = [[YWEquipmentFieldOption alloc] init];
            option.fieldOptionId = [set intForColumn:@"optionId"];
            option.fieldOptionText = [set stringForColumn:@"optionText"];
            fieldRecord.fieldOption = option;
            [fieldRecordArray addObject:fieldRecord];
        }
        [db closeOpenResultSets];
    }];
    return fieldRecordArray;
}
#pragma mark - dict_equipment_rule table
/**
 *  名称	设备业务规则字典表 dict_equipment_rule
 */
- (BOOL)createDictEquipmentRuleTable
{
    NSString* sql = @"CREATE TABLE 'dict_equipment_rule' (equipmentRuleId integer NOT NULL UNIQUE,content varchar(255));";
    return [_fmdb executeUpdate:sql];
}

- (void)updateDictEquipmentRule:(YWDictEquipmentRule*)dictEquipmentRule
{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipment_rule' WHERE equipmentRuleId=? ;";
        FMResultSet* set = [db executeQuery:sql, @(dictEquipmentRule.equipmentRuleId)];

        if ([set next]) {
            sql = @"UPDATE 'dict_equipment_rule' SET content=? WHERE equipmentRuleId=?;";
            [db executeUpdate:sql, dictEquipmentRule.content, @(dictEquipmentRule.equipmentRuleId)];
        }
        else {
            sql = @"INSERT INTO 'dict_equipment_rule' (equipmentRuleId, content) VALUES (?, ?);";
            [db executeUpdate:sql, @(dictEquipmentRule.equipmentRuleId), dictEquipmentRule.content];
        }

        [db closeOpenResultSets];
    }];
}

- (BOOL)insertDictEquipmentRuleWithArray:(NSArray*)dictEquipmentRule
{
    if (dictEquipmentRule.count==0) {
        return YES;
    }
    __block NSArray* blockDictEquipmentRule = dictEquipmentRule;
    __block BOOL executeResult = YES;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        __block NSString* sql = nil;
        sql = @"DELETE FROM 'dict_equipment_rule';";
        executeResult = [db executeUpdate:sql];
        if (!executeResult) {
            *rollback = YES;
        }

        [blockDictEquipmentRule enumerateObjectsUsingBlock:^(YWDictEquipmentRule* _Nonnull dictEquipmentRule, NSUInteger idx, BOOL* _Nonnull stop) {
//            sql = @"INSERT INTO 'dict_equipment_rule' (equipmentRuleId, content) VALUES (?, ?);";
//            BOOL result = [db executeUpdate:sql, @(dictEquipmentRule.equipmentRuleId), dictEquipmentRule.content];
//            if (!result) {
//                *stop = YES;
//                *rollback = YES;
//                executeResult = NO;
//            };
            sql = @"SELECT * FROM 'dict_equipment_rule' WHERE equipmentRuleId=? ;";
            FMResultSet* set = [db executeQuery:sql, @(dictEquipmentRule.equipmentRuleId)];
            
            if ([set next]) {
                sql = @"UPDATE 'dict_equipment_rule' SET content=? WHERE equipmentRuleId=?;";
                executeResult = [db executeUpdate:sql, dictEquipmentRule.content, @(dictEquipmentRule.equipmentRuleId)];
            }
            else {
                sql = @"INSERT INTO 'dict_equipment_rule' (equipmentRuleId, content) VALUES (?, ?);";
                executeResult = [db executeUpdate:sql, @(dictEquipmentRule.equipmentRuleId), dictEquipmentRule.content];
            }
        }];

        [db closeOpenResultSets];
    }];
    return executeResult;
}
#pragma mark - equipment_rule_rel table
/**
 *  名称	设备-规则关系表 equipment_rule_rel
 */
- (BOOL)createEquipmentRuleRelTable
{
    NSString* sql = @"CREATE TABLE 'equipment_rule_rel' (id integer NOT NULL PRIMARY KEY UNIQUE,detId integer NOT NULL,dmrId integer NOT NULL,maintenanceCycleId integer,ruleId integer NOT NULL);";
    return [_fmdb executeUpdate:sql];
}

- (void)updateEquipmentRuleRel:(YWEquipmentRuleRel*)equipmentRuleRel
{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_rule_rel' WHERE id=?;";
        FMResultSet* set = [db executeQuery:sql, @(equipmentRuleRel.equipmentRuleId)];
        
        if ([set next]) {
            sql = @"UPDATE 'equipment_rule_rel' SET detId=?, dmrId=?, maintenanceCycleId=? WHERE ruleId=?;";
            [db executeUpdate:sql, @(equipmentRuleRel.equipmentTypeId), @(equipmentRuleRel.maintenanceTypeId),@(equipmentRuleRel.maintenanceCycleId),@(equipmentRuleRel.equipmentRuleId)];
        }
        else {
            sql = @"INSERT INTO 'equipment_rule_rel' (detId, dmrId, maintenanceCycleId,ruleId) VALUES (?, ?, ?, ?);";
            [db executeUpdate:sql, @(equipmentRuleRel.equipmentTypeId), @(equipmentRuleRel.maintenanceTypeId), @(equipmentRuleRel.maintenanceCycleId),@(equipmentRuleRel.equipmentRuleId)];
        }
        
        [db closeOpenResultSets];
    }];
}


- (NSArray *)rulesWithEquipmentTypeId:(NSInteger)equipmentTypeId maintenanceTypeId:(NSInteger)maintenanceTypeId maintenanceCycleId:(NSInteger)maintenanceCycleId{
    __block NSMutableArray* rules = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        //按照周期区分规则
        if (maintenanceCycleId) {
            sql = @"SELECT * FROM 'dict_equipment_rule' WHERE equipmentRuleId IN (SELECT ruleId FROM 'equipment_rule_rel' WHERE detId=? AND dmrId=? AND maintenanceCycleId=?);";
            set = [db executeQuery:sql, @(equipmentTypeId), @(maintenanceTypeId),@(maintenanceCycleId)];
        }else{
            //没有区分周期
            sql = @"SELECT * FROM 'dict_equipment_rule' WHERE equipmentRuleId IN (SELECT ruleId FROM 'equipment_rule_rel' WHERE detId=? AND dmrId=?);";
            set = [db executeQuery:sql, @(equipmentTypeId), @(maintenanceTypeId)];
        }
        
        while ([set next]) {
            YWDictEquipmentRule* rule = [[YWDictEquipmentRule alloc] init];
            rule.equipmentRuleId = [set intForColumn:@"equipmentRuleId"];
            rule.content = [set stringForColumn:@"content"];
            [rules addObject:rule];
        }
        [db closeOpenResultSets];
    }];
    return rules;
}

- (BOOL)insertEquipmentRuleRelWithArray:(NSArray*)equipmentRuleRelArray{
    if (equipmentRuleRelArray.count==0) {
        return YES;
    }
    __block NSArray* blockEquipmentRuleRelArray = equipmentRuleRelArray;
    __block BOOL executeResult = YES;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        __block NSString* sql = nil;
        sql = @"DELETE FROM 'equipment_rule_rel';";
        executeResult = [db executeUpdate:sql];
        if (!executeResult) {
            *rollback = YES;
        }
        [blockEquipmentRuleRelArray enumerateObjectsUsingBlock:^(YWEquipmentRuleRel* _Nonnull equipmentRuleRel, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"INSERT INTO 'equipment_rule_rel' (detId, dmrId, maintenanceCycleId,ruleId) VALUES (?, ?, ?, ?);";
            BOOL result = [db executeUpdate:sql, @(equipmentRuleRel.equipmentTypeId), @(equipmentRuleRel.maintenanceTypeId), @(equipmentRuleRel.maintenanceCycleId),@(equipmentRuleRel.equipmentRuleId)];
            if (!result) {
                *stop = YES;
                *rollback = YES;
                executeResult = NO;
            };
        }];

        [db closeOpenResultSets];
    }];
    return executeResult;
}


#pragma mark - 设备表
- (BOOL)createEquipmentTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'equipment' (equipmentId varchar(24) NOT NULL UNIQUE,equipmentName varchar(100) NOT NULL,ownCode varchar(50),factoryNumber varchar(100),buyDate timestamp,produceDate timestamp,installDate timestamp,durableYears integer,model varchar(100),equipmentTypeId integer NOT NULL,floorId integer NOT NULL,apartmentId integer NOT NULL,buildingId varchar (13) NOT NULL,manufacturerId integer,factoryName varchar(100),locationId integer NOT NULL,qrcodeId varchar(19),locationText text,coordinate text);";
    return [_fmdb executeUpdate:sql];
}
#pragma mark - 能源仪表扩展属性
- (BOOL)createMeterPropertyIdTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'meterProperty' (meterPropertyId integer,rate float,place text,companyName text,equipmentId varchar(24) NOT NULL UNIQUE);";
    return [_fmdb executeUpdate:sql];
}
#pragma mark - 设备的初始参数
- (BOOL)createEquipmentInitialParameterTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'equipment_initialParameter' (equipmentId integer,propertyId integer NOT NULL,propertyName varchar,propertyValue varchar,status smallint,required integer,createTime timestamp,updateTime timestamp);";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)isExistEquipmentWithQrcodeId:(NSString*)qrcodeId{
    __block BOOL ret = NO;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* selectSQL = @"SELECT * FROM equipment WHERE qrcodeId=?;";
        FMResultSet* set = [db executeQuery:selectSQL, qrcodeId];
        if ([set next]) {ret = YES;}
        [db closeOpenResultSets];
    }];
    return ret;
}

- (BOOL)isExistEquipmentWithLocationId:(NSInteger)locationId{
    __block BOOL ret = NO;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* selectSQL = @"SELECT * FROM equipment WHERE locationId=?;";
        FMResultSet* set = [db executeQuery:selectSQL, @(locationId)];
        if ([set next]) {ret = YES;}
        [db closeOpenResultSets];
    }];
    return ret;
}

- (BOOL)insertEquipmentWithArray:(NSArray*)equipmentsArray
{
    if (equipmentsArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSMutableArray* picturesArray = [NSMutableArray array];
    __block NSMutableArray* meterPropertyArray = [NSMutableArray array];
    __block NSMutableArray* initParameterArray = [NSMutableArray array];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        __block NSString* sql = @"DELETE FROM 'equipment'";
        executeResult = [db executeUpdate:sql];
        if (!executeResult) {
            *rollback = YES;
        }
        [equipmentsArray enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL* _Nonnull stop) {
            if (equipment.buildingId.length==0) {
                equipment.buildingId = @"";
                YWLog(@"json数据有错误,设备的buildingid是空的,equipmentId:%@",equipment.equipmentId);
            }
            sql = @"INSERT INTO 'equipment' (equipmentId,equipmentName,ownCode,factoryNumber,buyDate,produceDate,installDate,durableYears,model,equipmentTypeId,floorId,apartmentId,buildingId,manufacturerId,factoryName,locationId,qrcodeId,locationText,coordinate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
            executeResult = [db executeUpdate:sql, equipment.equipmentId, equipment.equipmentName, equipment.ownCode, equipment.factoryCode, @(equipment.buyDate), @(equipment.produceDate), @(equipment.installDate), @(equipment.durableYears), equipment.model, @(equipment.equipmentTypeId), @(equipment.floorId), @(equipment.apartmentId), equipment.buildingId, @(equipment.manufacturerId), equipment.factoryName, @(equipment.locationId), equipment.qrcodeId,equipment.locationText,equipment.coordinate];
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            sql = @"delete FROM 'picture' WHERE equipmentId=? AND pictureTroubleType=?";
            executeResult = [db executeUpdate:sql, equipment.equipmentId,@(YWPictureTroubleTypeEquipment)];
            [equipment.pictures enumerateObjectsUsingBlock:^(YWPicture*  _Nonnull picture, NSUInteger idx, BOOL * _Nonnull stop) {
                picture.pictureId = [NSString stringWithFormat:@"%lu_%@",(unsigned long)idx,equipment.equipmentId];
                picture.pictureName = equipment.equipmentName;
                picture.isLocalImage = NO;
                picture.uploadStatus = YWPictureUploadStatusSuccess;
                picture.equipmentId = equipment.equipmentId;
                picture.pictureTroubleType = YWPictureTroubleTypeEquipment;
            }];
            [picturesArray addObjectsFromArray:equipment.pictures];
            
            sql = @"delete FROM 'equipment_initialParameter' WHERE equipmentId=?";
            executeResult = [db executeUpdate:sql, equipment.equipmentId];
            [equipment.properties enumerateObjectsUsingBlock:^(YWEquipmentInitialParameter*  _Nonnull initialParameter, NSUInteger idx, BOOL * _Nonnull stop) {
                initialParameter.equipmentId = equipment.equipmentId;
            }];
            [initParameterArray addObjectsFromArray:equipment.properties];
            
            if (equipment.meterProperty) {
                [meterPropertyArray addObject:equipment.meterProperty];
            }
        }];
        [db closeOpenResultSets];
    }];
    //保存设备的图片
    [self updatePictureWithArray:picturesArray];
    //保存设备的初始参数
    [self savEquipmentInitParameterWithArray:initParameterArray];
    //保存能源仪表扩展属性
    [self updateMeterPropertyWithArray:meterPropertyArray];
    return executeResult;
}

- (void)saveQrcodeEquipmentsWithArray:(NSArray *)equipmentsArray{
    if (equipmentsArray.count == 0) {
        return;
    }
    __block BOOL executeResult = YES;
    __block NSMutableArray* picturesArray = [NSMutableArray array];
    __block NSMutableArray* meterPropertyArray = [NSMutableArray array];
    __block NSMutableArray* initParameterArray = [NSMutableArray array];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [equipmentsArray enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL* _Nonnull stop) {
            if (equipment.buildingId.length==0) {
                equipment.buildingId = @"";
                YWLog(@"扫码下载的设备有错误,equipmentId:%@",equipment.equipmentId);
            }
            NSString* sql = @"INSERT INTO 'equipment' (equipmentId,equipmentName,ownCode,factoryNumber,buyDate,produceDate,installDate,durableYears,model,equipmentTypeId,floorId,apartmentId,buildingId,manufacturerId,factoryName,locationId,qrcodeId,locationText,coordinate) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
            executeResult = [db executeUpdate:sql, equipment.equipmentId, equipment.equipmentName, equipment.ownCode, equipment.factoryCode, @(equipment.buyDate), @(equipment.produceDate), @(equipment.installDate), @(equipment.durableYears), equipment.model, @(equipment.equipmentTypeId), @(equipment.floorId), @(equipment.apartmentId), equipment.buildingId, @(equipment.manufacturerId), equipment.factoryName, @(equipment.locationId), equipment.qrcodeId,equipment.locationText,equipment.coordinate];
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            sql = @"delete FROM 'picture' WHERE equipmentId=? AND pictureTroubleType=?";
            executeResult = [db executeUpdate:sql, equipment.equipmentId,@(YWPictureTroubleTypeEquipment)];
            [equipment.pictures enumerateObjectsUsingBlock:^(YWPicture*  _Nonnull picture, NSUInteger idx, BOOL * _Nonnull stop) {
                picture.pictureId = [NSString stringWithFormat:@"%lu_%@",(unsigned long)idx,equipment.equipmentId];
                picture.pictureName = equipment.equipmentName;
                picture.isLocalImage = NO;
                picture.uploadStatus = YWPictureUploadStatusSuccess;
                picture.equipmentId = equipment.equipmentId;
                picture.pictureTroubleType = YWPictureTroubleTypeEquipment;
            }];
            [picturesArray addObjectsFromArray:equipment.pictures];
            
            sql = @"delete FROM 'equipment_initialParameter' WHERE equipmentId=?";
            executeResult = [db executeUpdate:sql, equipment.equipmentId];
            [equipment.properties enumerateObjectsUsingBlock:^(YWEquipmentInitialParameter*  _Nonnull initialParameter, NSUInteger idx, BOOL * _Nonnull stop) {
                initialParameter.equipmentId = equipment.equipmentId;
            }];
            [initParameterArray addObjectsFromArray:equipment.properties];
            
            if (equipment.meterProperty) {
                [meterPropertyArray addObject:equipment.meterProperty];
            }
        }];
        [db closeOpenResultSets];
    }];
    //保存设备的图片
    [self updatePictureWithArray:picturesArray];
    //保存设备的初始参数
    [self savEquipmentInitParameterWithArray:initParameterArray];
    //保存能源仪表扩展属性
    [self updateMeterPropertyWithArray:meterPropertyArray];
}

//初始化参数
- (BOOL)savEquipmentInitParameterWithArray:(NSArray*)initParameterArray{
    if (initParameterArray.count == 0) {
        return YES;
    }
    __block NSArray* blockInitParameterArray = initParameterArray;
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockInitParameterArray enumerateObjectsUsingBlock:^(YWEquipmentInitialParameter* _Nonnull initParameter, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"INSERT INTO 'equipment_initialParameter' (propertyId,propertyName,propertyValue,status,required,createTime,updateTime,equipmentId) VALUES (?,?,?,?,?,?,?,?);";
            executeResult = [db executeUpdate:sql, @(initParameter.propertyId), initParameter.propertyName, initParameter.propertyValue,@(initParameter.status), @(initParameter.required),@(initParameter.createTime),@(initParameter.updateTime),initParameter.equipmentId];
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray *)equipmentParametersWithEquipmentId:(NSString*)equipmentId{
    __block NSMutableArray* parametersArr = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_initialParameter' WHERE equipmentId = ? AND status=0";
        FMResultSet* set = [db executeQuery:sql, equipmentId];
        while ([set next]) {
            YWEquipmentInitialParameter* initParameter = [self equipmentInitParameterWithFMResultSet:set];
            [parametersArr addObject:initParameter];
        }
        [db closeOpenResultSets];
    }];
    return parametersArr;
}
- (YWEquipmentInitialParameter*)equipmentInitParameterWithFMResultSet:(FMResultSet*)set{
    YWEquipmentInitialParameter* initParameter = [[YWEquipmentInitialParameter alloc] init];
    initParameter.propertyId = [set intForColumn:@"propertyId"];
    initParameter.propertyName = [set stringForColumn:@"propertyName"];
    initParameter.propertyValue = [set stringForColumn:@"propertyValue"];
    initParameter.status = [set intForColumn:@"status"];
    initParameter.required = [set intForColumn:@"required"];
    initParameter.createTime = [set longLongIntForColumn:@"createTime"];
    initParameter.updateTime = [set longLongIntForColumn:@"updateTime"];
    initParameter.equipmentId = [set stringForColumn:@"equipmentId"];
    return initParameter;
}
//能源仪表扩展属性
- (BOOL)updateMeterPropertyWithArray:(NSArray*)array{
    if (array.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockMeterPropertyArray = array;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        __block NSString* sql = nil;
        [blockMeterPropertyArray enumerateObjectsUsingBlock:^(YWMeterProperty* _Nonnull meterProperty, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"DELETE FROM 'meterProperty' where equipmentId=?;";
            executeResult = [db executeUpdate:sql, meterProperty.equipmentId];
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
                executeResult = NO;
            }
            sql = @"INSERT INTO 'meterProperty' (meterPropertyId,rate,place,companyName,equipmentId) VALUES (?,?,?,?,?);";
            BOOL result = [db executeUpdate:sql, @(meterProperty.meterPropertyId),@(meterProperty.rate),meterProperty.place,meterProperty.companyName,meterProperty.equipmentId];
            if (!result) {
                *stop = YES;
                *rollback = YES;
                executeResult = NO;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (YWMeterProperty *)meterPropertyWithEquipmentId:(NSString*)equipmentId{
    __block YWMeterProperty* meterProperty = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'meterProperty' WHERE equipmentId = ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId];
        if ([set next]) {
            meterProperty = [self meterPropertyWithFMResultSet:set];
        }
        [db closeOpenResultSets];
    }];
    return meterProperty;
}

- (YWMeterProperty*)meterPropertyWithFMResultSet:(FMResultSet*)set{
    YWMeterProperty *meterProperty = [[YWMeterProperty alloc] init];
    meterProperty.meterPropertyId = [set intForColumn:@"meterPropertyId"];
    meterProperty.rate = [set doubleForColumn:@"rate"];
    meterProperty.place = [set stringForColumn:@"place"];
    meterProperty.companyName = [set stringForColumn:@"companyName"];
    meterProperty.equipmentId = [set stringForColumn:@"equipmentId"];
    return meterProperty;
}

- (YWEquipment*)equipmentWithFMResultSet:(FMResultSet*)set
{
    YWEquipment* equipment = [[YWEquipment alloc] init];
    equipment.equipmentId = [set stringForColumn:@"equipmentId"];
    equipment.equipmentName = [set stringForColumn:@"equipmentName"];
    equipment.ownCode = [set stringForColumn:@"ownCode"];
    equipment.factoryCode = [set stringForColumn:@"factoryNumber"];
    equipment.buyDate = [set longLongIntForColumn:@"buyDate"];
    equipment.produceDate = [set longLongIntForColumn:@"produceDate"];
    equipment.installDate = [set longLongIntForColumn:@"installDate"];
    equipment.durableYears = [set intForColumn:@"durableYears"];
    equipment.model = [set stringForColumn:@"model"];
    equipment.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
    equipment.buildingId = [set stringForColumn:@"buildingId"];
    equipment.apartmentId = [set intForColumn:@"apartmentId"];
    equipment.floorId = [set intForColumn:@"floorId"];
    equipment.locationId = [set intForColumn:@"locationId"];
    equipment.manufacturerId = [set intForColumn:@"manufacturerId"];
    equipment.factoryName = [set stringForColumn:@"factoryName"];
    equipment.qrcodeId = [set stringForColumn:@"qrcodeId"];
    equipment.locationText = [set stringForColumn:@"locationText"];
    equipment.coordinate = [set stringForColumn:@"coordinate"];
    return equipment;
}

- (YWEquipment*)equipmentWithOwncode:(NSString*)ownCode
{
    __block YWEquipment* equipment = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment' WHERE ownCode = ?;";
        FMResultSet* set = [db executeQuery:sql, ownCode];
        if ([set next]) {
            equipment = [self equipmentWithFMResultSet:set];
        }
        [db closeOpenResultSets];
    }];
    return equipment;
}

- (YWEquipmentType*)equipmentTypeWithEquipmentTypeId:(NSInteger)equipmentTypeId{
    
    __block YWEquipmentType* equipmentType = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'dict_equipment_type' WHERE equipmentTypeId=?;";
        FMResultSet* set = [db executeQuery:sql, @(equipmentTypeId)];
        if ([set next]) {
            equipmentType = [self equipmentTypeWithFMResultSet:set db:db];
        }
        [db closeOpenResultSets];
    }];
    return equipmentType;
}

- (YWEquipment*)equipmentWithId:(NSString*)equipmentId
{
    __block YWEquipment* equipment = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment' WHERE equipmentId = ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId];
        if ([set next]) {
            equipment = [self equipmentWithFMResultSet:set];
        }
        [db closeOpenResultSets];
    }];
    return equipment;
}

- (NSArray*)qrcodeEquipmentInfos:(NSString*)qrcodeId
{
    __block NSMutableArray* qrcodeEquipmentInfos = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT count(*) equipentCount,equipmentTypeId,qrcodeId,locationId FROM 'equipment' WHERE qrcodeId=? GROUP BY equipmentTypeId;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId];
        while ([set next]) {

            YWQrcodeEquipmentInfo* qrcodeEquipmentInfo = [[YWQrcodeEquipmentInfo alloc] init];
            qrcodeEquipmentInfo.equipmentCount = [set intForColumn:@"equipentCount"];
            qrcodeEquipmentInfo.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
            qrcodeEquipmentInfo.qrcodeId = [set stringForColumn:@"qrcodeId"];
            qrcodeEquipmentInfo.locationId = [set intForColumn:@"locationId"];
            [qrcodeEquipmentInfos addObject:qrcodeEquipmentInfo];
        }
        [db closeOpenResultSets];
    }];
    return qrcodeEquipmentInfos;
}

- (NSArray*)qrcodeEquipmentInfos:(NSString*)qrcodeId orLocationId:(NSInteger)locationId equipmentTypeId:(NSInteger)equipmentTypeId
{
    __block NSMutableArray* qrcodeEquipmentInfos = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (qrcodeId) {
            sql = @"SELECT count(*) equipentCount,equipmentTypeId,qrcodeId FROM 'equipment' WHERE qrcodeId=? AND equipmentTypeId=?";
            set = [db executeQuery:sql, qrcodeId, @(equipmentTypeId)];
        }else if (locationId){
            sql = @"SELECT count(*) equipentCount,equipmentTypeId,qrcodeId FROM 'equipment' WHERE locationId=? AND equipmentTypeId=?";
            set = [db executeQuery:sql, @(locationId), @(equipmentTypeId)];
        }
        while ([set next]) {
            YWQrcodeEquipmentInfo* qrcodeEquipmentInfo = [[YWQrcodeEquipmentInfo alloc] init];
            qrcodeEquipmentInfo.equipmentCount = [set intForColumn:@"equipentCount"];
            qrcodeEquipmentInfo.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
            qrcodeEquipmentInfo.qrcodeId = [set stringForColumn:@"qrcodeId"];
            [qrcodeEquipmentInfos addObject:qrcodeEquipmentInfo];
        }
        [db closeOpenResultSets];
    }];
    return qrcodeEquipmentInfos;
}

- (NSArray*)equipmentWithQrcodeId:(NSString*)qrcodeId orLocationId:(NSInteger)locationId equipmentTypeId:(NSInteger)equipmentTypeId
{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        FMResultSet* set = nil;
        NSString* sql = nil;
        if (qrcodeId) {
            sql = @"SELECT * FROM 'equipment' WHERE qrcodeId=? AND equipmentTypeId=?;";
            set = [db executeQuery:sql, qrcodeId, @(equipmentTypeId)];
        }else if (locationId){
            sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId=?;";
            set = [db executeQuery:sql, @(locationId), @(equipmentTypeId)];
        }
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            [equipments addObject:equipment];
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}

- (NSArray*)equipmentWithQrcodeId:(NSString*)qrcodeId
{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment' WHERE qrcodeId=? order by equipmentTypeId;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId];
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            [equipments addObject:equipment];
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}
- (NSArray*)equipmentInNoQrcodeLedgerWithQrcodeId:(NSString*)qrcodeId{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE qrcodeId=? GROUP BY equipmentTypeId";
//        NSString* sql = @"SELECT * FROM 'equipment' WHERE qrcodeId=?;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId];
        while ([set next]) {
            
            YWQrcodeEquipmentInfo* qrcodeEquipmentInfo = [[YWQrcodeEquipmentInfo alloc] init];
            qrcodeEquipmentInfo.equipmentCount = [set intForColumn:@"equipentCount"];
            qrcodeEquipmentInfo.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
            qrcodeEquipmentInfo.locationId = [set intForColumn:@"locationId"];
            [equipments addObject:qrcodeEquipmentInfo];
        }

//        NSInteger lastEquipmentTypeId = 0;
//        NSMutableArray *array = nil;
//        while ([set next]) {
//            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
//            NSInteger equipmentTypeId = equipment.equipmentTypeId;
//            if (lastEquipmentTypeId==0 || equipmentTypeId !=lastEquipmentTypeId) {
//                lastEquipmentTypeId = equipmentTypeId;
//                array = [NSMutableArray array];
//            }
//            [array addObject:equipment];
//            if (![equipments containsObject:array]) {
//                [equipments addObject:array];
//            }
//        }
        [db closeOpenResultSets];
    }];
    return equipments;
}
- (NSArray*)equipmentTypeArrayWithLocationId:(NSInteger)locationId AndEquipmentTypeId:(NSInteger)equipmentTypeId{
    
    __block NSMutableArray* equipmentTypeArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        FMResultSet* set = nil;
        if (equipmentTypeId == 0) {
            NSString* sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE locationId=? GROUP BY equipmentTypeId;";
            set = [db executeQuery:sql, @(locationId)];
        }else{
            NSString* sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE locationId=? And equipmentTypeId =? GROUP BY equipmentTypeId;";
            set = [db executeQuery:sql, @(locationId),@(equipmentTypeId)];
        }
        while ([set next]) {
            
            YWQrcodeEquipmentInfo* qrcodeEquipmentInfo = [[YWQrcodeEquipmentInfo alloc] init];
            qrcodeEquipmentInfo.equipmentCount = [set intForColumn:@"equipentCount"];
            qrcodeEquipmentInfo.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
            qrcodeEquipmentInfo.locationId = [set intForColumn:@"locationId"];
            [equipmentTypeArray addObject:qrcodeEquipmentInfo];
        }
        [db closeOpenResultSets];
    }];
    return equipmentTypeArray;
}

- (NSArray*)equipmentTypeArrayWithQrcodeId:(NSString*)qrcodeId{
    __block NSMutableArray* equipmentTypeArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE qrcodeId=? GROUP BY equipmentTypeId;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId];
        while ([set next]) {
            
            YWQrcodeEquipmentInfo* qrcodeEquipmentInfo = [[YWQrcodeEquipmentInfo alloc] init];
            qrcodeEquipmentInfo.equipmentCount = [set intForColumn:@"equipentCount"];
            qrcodeEquipmentInfo.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
            qrcodeEquipmentInfo.locationId = [set intForColumn:@"locationId"];
            [equipmentTypeArray addObject:qrcodeEquipmentInfo];
        }
        [db closeOpenResultSets];
    }];
    return equipmentTypeArray;
}

- (NSArray*)equipmentArrayWithLocationId:(NSInteger)locationId{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment' WHERE locationId =? order by equipmentTypeId";
        FMResultSet* set = [db executeQuery:sql, @(locationId)];
        NSInteger lastEquipmentTypeId = 0;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            NSInteger equipmentTypeId = equipment.equipmentTypeId;
            if (lastEquipmentTypeId==0 || equipmentTypeId != lastEquipmentTypeId) {
                lastEquipmentTypeId = equipmentTypeId;
                array = [NSMutableArray array];
            }
            [array addObject:equipment];
            if (![equipments containsObject:array] && array.count) {
                [equipments addObject:array];
            }
        }
        
        [db closeOpenResultSets];
    }];
    return equipments;
}

- (NSArray *)equipmentWithLocationId:(NSInteger)locationId{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment' WHERE locationId =? order by equipmentTypeId";
        FMResultSet* set = [db executeQuery:sql, @(locationId)];
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            [equipments addObject:equipment];
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}

- (NSArray *)equipmentsWithBuildingId:(NSString *)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId page:(NSInteger)page{
    __block NSInteger showCount = page * 20;
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(showCount)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(showCount)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(showCount)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? ORDER BY equipmentId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(showCount)];
            }
        }
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            [equipments addObject:equipment];
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}
- (NSArray *)equipmentArrayWithBuildingId:(NSString *)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId page:(NSInteger)page{
    __block NSInteger showCount = page * 20;
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(showCount)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(showCount)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(showCount)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? ORDER BY equipmentTypeId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(showCount)];
            }
        }
        NSInteger lastEquipmentTypeId = 0;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            NSInteger equipmentTypeId = equipment.equipmentTypeId;
            if (lastEquipmentTypeId==0 || equipmentTypeId !=lastEquipmentTypeId) {
                lastEquipmentTypeId = equipmentTypeId;
                array = [NSMutableArray array];
            }
            [array addObject:equipment];
            if (![equipments containsObject:array] && array.count) {
                [equipments addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}

- (NSArray*)equipmentTypesWithLocationId:(NSInteger)locationId orBuildingId:(NSString*)buildingId{
    __block NSMutableArray* equipmentTypes = [NSMutableArray array];
    if (locationId>0) {
        [self.dbQeue inDatabase:^(FMDatabase* db) {
            NSString* sql = @"SELECT * FROM 'dict_equipment_type' WHERE equipmentTypeId in (SELECT distinct equipmentTypeId FROM 'equipment' WHERE locationId = ?)";
            FMResultSet* set = [db executeQuery:sql, @(locationId)];
            while ([set next]) {
                YWEquipmentType* equipmentType = [self equipmentTypeWithFMResultSet:set db:db];
                [equipmentTypes addObject:equipmentType];
            }
            [db closeOpenResultSets];
        }];
    }else{
        [self.dbQeue inDatabase:^(FMDatabase* db) {
            NSString* sql = @"SELECT * FROM 'dict_equipment_type' WHERE equipmentTypeId in (SELECT distinct equipmentTypeId FROM 'equipment' WHERE buildingId = ?)";
            FMResultSet* set = [db executeQuery:sql,buildingId];
            while ([set next]) {
                YWEquipmentType* equipmentType = [self equipmentTypeWithFMResultSet:set db:db];
                [equipmentTypes addObject:equipmentType];
            }
            [db closeOpenResultSets];
        }];
    }
        return equipmentTypes;
}

- (NSArray *)equipmentArrayWithBuildingId:(NSString *)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
               sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? ORDER BY equipmentTypeId ";
                set = [db executeQuery:sql, @(locationId)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? ORDER BY equipmentTypeId ";
                set = [db executeQuery:sql, @(floorId)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId ";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId];
            }
        }
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            [equipments addObject:equipment];
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}

- (NSArray *)equipmentInfoArrayWithBuildingId:(NSString *)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId{
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE locationId=? AND equipmentTypeId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE locationId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE floorId=? AND equipmentTypeId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE floorId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE apartmentId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(*) equipentCount,equipmentTypeId,locationId FROM 'equipment' WHERE buildingId=? GROUP BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId];
            }
        }
        while ([set next]) {
            
            YWQrcodeEquipmentInfo* qrcodeEquipmentInfo = [[YWQrcodeEquipmentInfo alloc] init];
            qrcodeEquipmentInfo.equipmentCount = [set intForColumn:@"equipentCount"];
            qrcodeEquipmentInfo.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
            qrcodeEquipmentInfo.locationId = [set intForColumn:@"locationId"];
            [equipments addObject:qrcodeEquipmentInfo];
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}


- (NSInteger)equipmentCountWithBuildingId:(NSString*)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId{
    __block NSInteger equipmentCount = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE locationId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE locationId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(locationId)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT COUNT(*) equipmentCount FROM  'equipment' WHERE floorId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE floorId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(floorId)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE apartmentId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, @(apartmentId)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId)];
            }else{
                sql = @"SELECT COUNT(*) equipmentCount FROM 'equipment' WHERE buildingId=? ORDER BY equipmentTypeId";
                set = [db executeQuery:sql, buildingId];
            }
        }
        if ([set next]) {
            equipmentCount = [set longForColumn:@"equipmentCount"];
        }
            [db closeOpenResultSets];
    }];
    return equipmentCount;
}

- (NSInteger)qrcodeCountWithBuildingId:(NSString*)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId{
    __block NSInteger qrcodeCount = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE locationId=? AND equipmentTypeId=?";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?)";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE locationId=?";
                set = [db executeQuery:sql, @(locationId)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE floorId=? AND equipmentTypeId=?";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?)";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE floorId=?";
                set = [db executeQuery:sql, @(floorId)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=?";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?)";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE apartmentId=?";
                set = [db executeQuery:sql, @(apartmentId)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=?";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?)";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId)];
            }else{
                sql = @"SELECT count(distinct qrcodeId) AS qrcodeIdCount  FROM 'equipment' WHERE buildingId=?";
                set = [db executeQuery:sql, buildingId];
            }
        }
        if ([set next]) {
            qrcodeCount = [set longForColumn:@"qrcodeIdCount"];
        }
        [db closeOpenResultSets];
    }];
    return qrcodeCount;
}

- (NSArray *)equipmentArrayOrderByLocationIdWithBuildingId:(NSString *)buildingId ApartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId locationId:(NSInteger)locationId eqipmentSubSystemType:(NSInteger)SubSystemTypeId equipmentTypeId:(NSInteger)equipmentTypeId  page:(NSInteger)page{
    __block NSInteger showCount = page * 10;
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (locationId>0) {
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId=? ORDER BY equipmentTypeId,apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE locationId=? ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(locationId),@(showCount)];
            }
            
        }else if (floorId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId=? ORDER BY equipmentTypeId,apartmentId,floorId,locationId      LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE floorId=? ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(floorId),@(showCount)];
            }
        }else if (apartmentId>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId=? ORDER BY equipmentTypeId,apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE apartmentId=? ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, @(apartmentId),@(showCount)];
            }
        }else if (buildingId.length>0){
            if (equipmentTypeId>0) {
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId=? ORDER BY equipmentTypeId,apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(equipmentTypeId),@(showCount)];
            }else if (SubSystemTypeId>0){
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? AND equipmentTypeId IN (SELECT equipmentTypeId FROM 'dict_equipment_type' WHERE status=0 AND subSystemTypeId=?) ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(SubSystemTypeId),@(showCount)];
            }else{
                sql = @"SELECT * FROM 'equipment' WHERE buildingId=? ORDER BY apartmentId,floorId,locationId LIMIT ?";
                set = [db executeQuery:sql, buildingId,@(showCount)];
            }
        }
        NSInteger lastLocationId = 0;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            NSInteger locationId = equipment.locationId;
            if (lastLocationId==0 || locationId !=lastLocationId) {
                lastLocationId = locationId;
                array = [NSMutableArray array];
            }
            [array addObject:equipment];
            if (![equipments containsObject:array] && array.count) {
                [equipments addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}

#pragma mark - building table

NSString *const KSqlCreateBuildingTable = @"CREATE TABLE IF NOT EXISTS 'building' (buildingId varchar NOT NULL,buildingName varchar NOT NULL,foundDate timestamp,contact varchar,contactNumber varchar,address varchar,floorArea integer,buildingArea integer,coordinate varchar,durableYears integer,surfacePicture varchar,equipmentJsonFileUpdateTime timestamp,buildingJsonFileUpdateTime timestamp,ruleJsonFileUpdateTime timestamp);";

- (BOOL)createbuildingTable{
    return [_fmdb executeUpdate:KSqlCreateBuildingTable];
}

- (void)dropAndReCreateBuildingTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists building;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateBuildingTable];
        }
    }];
}

- (BOOL)insertbuildingWithArray:(NSArray*)buildingJsonArray{
    __block BOOL executeResult = YES;
    __block NSArray* blockbuildingJsonArray = buildingJsonArray;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        __block NSString* sql = nil;
//        [blockbuildingJsonArray enumerateObjectsUsingBlock:^(YWBuildingJson* _Nonnull buildingJson, NSUInteger idx, BOOL* _Nonnull stop) {
//            sql = @"DELETE FROM 'building' WHERE buildingId=?;";
//            executeResult = [db executeUpdate:sql, buildingJson.buildingId];
//            if (!executeResult) {
//                *rollback = YES;
//            }
//        }];
        sql = @"DELETE FROM 'building'";
        executeResult = [db executeUpdate:sql];
        if (!executeResult) {
            *rollback = YES;
        }
        [blockbuildingJsonArray enumerateObjectsUsingBlock:^(YWBuildingJson* _Nonnull buildingJson, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString *sql = @"SELECT * FROM 'building' WHERE buildingId=?;";
            FMResultSet* set = [db executeQuery:sql, buildingJson.buildingId];
            if (![set next]) {
                sql = @"INSERT INTO 'building' (buildingId,buildingName,foundDate,contact,contactNumber,address,floorArea,buildingArea,coordinate,durableYears,surfacePicture,buildingJsonFileUpdateTime,equipmentJsonFileUpdateTime,ruleJsonFileUpdateTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, buildingJson.buildingId, buildingJson.buildingName, @(buildingJson.foundDate), buildingJson.contact, buildingJson.contactNumber, buildingJson.address, @(buildingJson.floorArea), @(buildingJson.buildingArea), buildingJson.coordinate, @(buildingJson.durableYears), buildingJson.surfacePicture, @(buildingJson.buildingJsonFileUpdateTime), @(buildingJson.equipmentJsonFileUpdateTime), @(buildingJson.ruleJsonFileUpdateTime)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];

        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updatebuildingWithJsonArray:(NSArray*)buildingJsonArray{
    if (buildingJsonArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockBuildingJsonArray = buildingJsonArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockBuildingJsonArray enumerateObjectsUsingBlock:^(YWBuildingJson* _Nonnull buildingJson, NSUInteger idx, BOOL* _Nonnull stop) {
            //楼盘
            sql = @"SELECT * FROM 'building' WHERE buildingId=?;";
            FMResultSet* set = [db executeQuery:sql, buildingJson.buildingId];
            ////没有更新buildingJsonFileUpdateTime的两个时间，因为这里没有值所以不去更新
            if ([set next]) {
//                sql = @"UPDATE 'building' SET buildingName=?,foundDate=?,contact=?,contactNumber=?,address=?,floorArea=?,buildingArea=?,coordinate=?,durableYears=?,surfacePicture=? WHERE buildingId=?;";
//                executeResult = [db executeUpdate:sql, buildingJson.buildingName, @(buildingJson.foundDate), buildingJson.contact, buildingJson.contactNumber, buildingJson.address, @(buildingJson.floorArea), @(buildingJson.buildingArea), buildingJson.coordinate, @(buildingJson.durableYears), buildingJson.surfacePicture, buildingJson.buildingId];
                sql = @"UPDATE 'building' SET buildingName=? WHERE buildingId=?;";
                executeResult = [db executeUpdate:sql, buildingJson.buildingName, buildingJson.buildingId];
            }
            else {
//                sql = @"INSERT INTO 'building' (buildingId,buildingName,foundDate,contact,contactNumber,address,floorArea,buildingArea,coordinate,durableYears,surfacePicture,buildingJsonFileUpdateTime,equipmentJsonFileUpdateTime,ruleJsonFileUpdateTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
//                executeResult = [db executeUpdate:sql, buildingJson.buildingId, buildingJson.buildingName, @(buildingJson.foundDate), buildingJson.contact, buildingJson.contactNumber, buildingJson.address, @(buildingJson.floorArea), @(buildingJson.buildingArea), buildingJson.coordinate, @(buildingJson.durableYears), buildingJson.surfacePicture, @(buildingJson.buildingJsonFileUpdateTime), @(buildingJson.equipmentJsonFileUpdateTime), @(buildingJson.ruleJsonFileUpdateTime)];
                //不插入，防止未授权楼盘
//                sql = @"INSERT INTO 'building' (buildingId,buildingName) VALUES (?,?);";
//                executeResult = [db executeUpdate:sql, buildingJson.buildingId, buildingJson.buildingName];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            //楼栋
            [buildingJson.apartments enumerateObjectsUsingBlock:^(YWApartmentJson* _Nonnull apartmentJson, NSUInteger idx, BOOL* _Nonnull stop) {
                sql = @"SELECT * FROM 'apartment' WHERE apartmentId=?;";
                FMResultSet* set = [db executeQuery:sql, @(apartmentJson.apartmentId)];
                if ([set next]) {
//                    sql = @"UPDATE 'apartment' SET apartmentName=?,code=?,overgroundCount=?,undergroundCount=?,durableYears=?,buildingId=? WHERE apartmentId=?;";
//                    executeResult = [db executeUpdate:sql, apartmentJson.apartmentName, apartmentJson.code, @(apartmentJson.overgroundCount), @(apartmentJson.undergroundCount), @(apartmentJson.durableYears), buildingJson.buildingId, @(apartmentJson.apartmentId)];
                    sql = @"UPDATE 'apartment' SET apartmentName=?,buildingId=? WHERE apartmentId=?;";
                    executeResult = [db executeUpdate:sql, apartmentJson.apartmentName, buildingJson.buildingId, @(apartmentJson.apartmentId)];
                }
                else {
//                    sql = @"INSERT INTO 'apartment' (apartmentId,apartmentName,code,overgroundCount,undergroundCount,durableYears,buildingId) VALUES (?,?,?,?,?,?,?);";
//                    executeResult = [db executeUpdate:sql, @(apartmentJson.apartmentId), apartmentJson.apartmentName, apartmentJson.code, @(apartmentJson.overgroundCount), @(apartmentJson.undergroundCount), @(apartmentJson.durableYears), buildingJson.buildingId];
                    sql = @"INSERT INTO 'apartment' (apartmentId,apartmentName,buildingId) VALUES (?,?,?);";
                    executeResult = [db executeUpdate:sql, @(apartmentJson.apartmentId), apartmentJson.apartmentName, buildingJson.buildingId];
                }
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                };
                //楼层
                [apartmentJson.floors enumerateObjectsUsingBlock:^(YWFloorJson* _Nonnull floorJson, NSUInteger idx, BOOL* _Nonnull stop) {
                    sql = @"SELECT * FROM 'floor' WHERE floorId=?;";
                    FMResultSet* set = [db executeQuery:sql, @(floorJson.floorId)];
                    if ([set next]) {
//                        sql = @"UPDATE 'floor' SET floorName=?,code=?,height=?,apartmentId=? WHERE floorId=?;";
//                        executeResult = [db executeUpdate:sql, floorJson.floorName, floorJson.code, @(floorJson.height), @(apartmentJson.apartmentId), @(floorJson.floorId)];
                        sql = @"UPDATE 'floor' SET floorName=?,apartmentId=? WHERE floorId=?;";
                        executeResult = [db executeUpdate:sql, floorJson.floorName, @(apartmentJson.apartmentId), @(floorJson.floorId)];
                    }else {
//                        sql = @"INSERT INTO 'floor' (floorId,floorName,code,height,apartmentId) VALUES (?,?,?,?,?);";
//                        executeResult = [db executeUpdate:sql, @(floorJson.floorId), floorJson.floorName, floorJson.code, @(floorJson.height), @(apartmentJson.apartmentId)];
                        sql = @"INSERT INTO 'floor' (floorId,floorName,apartmentId) VALUES (?,?,?);";
                        executeResult = [db executeUpdate:sql, @(floorJson.floorId), floorJson.floorName, @(apartmentJson.apartmentId)];
                    }
                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    };
                    //层位置
                    [floorJson.locations enumerateObjectsUsingBlock:^(YWLocationJson* _Nonnull locationJson, NSUInteger idx, BOOL* _Nonnull stop) {
                        sql = @"SELECT * FROM 'location' WHERE locationId=?;";
                        FMResultSet* set = [db executeQuery:sql, @(locationJson.locationId)];
                        if ([set next]) {
//                            sql = @"UPDATE 'location' SET locationName=?, code=?, floorId=? WHERE locationId=?;";
//                            executeResult = [db executeUpdate:sql, locationJson.locationName, locationJson.code, @(floorJson.floorId), @(locationJson.locationId)];
                            sql = @"UPDATE 'location' SET locationName=?,floorId=? WHERE locationId=?;";
                            executeResult = [db executeUpdate:sql, locationJson.locationName, @(floorJson.floorId), @(locationJson.locationId)];
                        }else {
//                            sql = @"INSERT INTO 'location' (locationId, locationName , code , floorId ) VALUES (?,?,?,?);";
//                            executeResult = [db executeUpdate:sql, @(locationJson.locationId), locationJson.locationName, locationJson.code, @(floorJson.floorId)];
                            sql = @"INSERT INTO 'location' (locationId, locationName , floorId ) VALUES (?,?,?);";
                            executeResult = [db executeUpdate:sql, @(locationJson.locationId), locationJson.locationName, @(floorJson.floorId)];
                        }
                        if (!executeResult) {
                            *stop = YES;
                            *rollback = YES;
                        };
                    }];
                }];

            }];

        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateIdAndNameWithBuilding:(YWBuilding *)building apartment:(YWApartment *)apartment floor:(YWFloor *)floor location:(YWLocation *)location{
    if (!building || !apartment || !floor || !location) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        //楼盘
        sql = @"SELECT * FROM 'building' WHERE buildingId=?;";
        FMResultSet* set = [db executeQuery:sql, building.buildingId];
        if ([set next]) {
            sql = @"UPDATE 'building' SET buildingName=? WHERE buildingId=?;";
            executeResult = [db executeUpdate:sql, building.buildingName, building.buildingId];
        }
        //不插入，防止未授权楼盘
//        else {
//            sql = @"INSERT INTO 'building' (buildingId,buildingName) VALUES (?,?);";
//            executeResult = [db executeUpdate:sql, building.buildingId, building.buildingName];
//        }
        if (!executeResult) {
            *rollback = YES;
        };
        //楼栋
        sql = @"SELECT * FROM 'apartment' WHERE apartmentId=?;";
        set = [db executeQuery:sql, @(apartment.apartmentId)];
        if ([set next]) {
            sql = @"UPDATE 'apartment' SET apartmentName=?,buildingId=? WHERE apartmentId=?;";
            executeResult = [db executeUpdate:sql, apartment.apartmentName, building.buildingId, @(apartment.apartmentId)];
        }
        else {
            sql = @"INSERT INTO 'apartment' (apartmentId,apartmentName,buildingId) VALUES (?,?,?);";
            executeResult = [db executeUpdate:sql, @(apartment.apartmentId), apartment.apartmentName, building.buildingId];
        }
        if (!executeResult) {
            *rollback = YES;
        };
        //楼层
        sql = @"SELECT * FROM 'floor' WHERE floorId=?;";
        set = [db executeQuery:sql, @(floor.floorId)];
        if ([set next]) {
            sql = @"UPDATE 'floor' SET floorName=?,apartmentId=? WHERE floorId=?;";
            executeResult = [db executeUpdate:sql, floor.floorName, @(apartment.apartmentId), @(floor.floorId)];
        }else {
            sql = @"INSERT INTO 'floor' (floorId,floorName,apartmentId) VALUES (?,?,?);";
            executeResult = [db executeUpdate:sql, @(floor.floorId), floor.floorName, @(apartment.apartmentId)];
        }
        if (!executeResult) {
            *rollback = YES;
        };
        //位置
        sql = @"SELECT * FROM 'location' WHERE locationId=?;";
        set = [db executeQuery:sql, @(location.locationId)];
        if ([set next]) {
            sql = @"UPDATE 'location' SET locationName=?,floorId=? WHERE locationId=?;";
            executeResult = [db executeUpdate:sql, location.locationName, @(floor.floorId), @(location.locationId)];
        }else {
            sql = @"INSERT INTO 'location' (locationId, locationName , floorId ) VALUES (?,?,?);";
            executeResult = [db executeUpdate:sql, @(location.locationId), location.locationName, @(floor.floorId)];
        }
        if (!executeResult) {
            *rollback = YES;
        };
        [db closeOpenResultSets];
    }];
    return executeResult;
}

//- (BOOL)updateBuildingWithArray:(NSArray*)buildingsArray{
//    if (buildingsArray.count == 0) {
//        return YES;
//    }
//    __block BOOL executeResult = YES;
//    __block NSArray* blockBuildingsArray = buildingsArray;
//    __block NSString* sql = nil;
//    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
//        [blockBuildingsArray enumerateObjectsUsingBlock:^(YWBuilding* _Nonnull building, NSUInteger idx, BOOL* _Nonnull stop) {
//            sql = @"SELECT * FROM 'building' WHERE buildingId=?;";
//            FMResultSet* set = [db executeQuery:sql, building.buildingId];
//            ////没有更新buildingJsonFileUpdateTime的两个时间，因为这里没有值所以不去更新
//            if ([set next]) {
//                sql = @"UPDATE 'building' SET buildingName=?,foundDate=?,contact=?,contactNumber=?,address=?,floorArea=?,buildingArea=?,coordinate=?,durableYears=?,surfacePicture=? WHERE buildingId=?;";
//                executeResult = [db executeUpdate:sql, building.buildingName, @(building.foundDate), building.contact, building.contactNumber, building.address, @(building.floorArea), @(building.buildingArea), building.coordinate, @(building.durableYears), building.surfacePicture, building.buildingId];
//            }else {
//                sql = @"INSERT INTO 'building' (buildingId,buildingName,foundDate,contact,contactNumber,address,floorArea,buildingArea,coordinate,durableYears,surfacePicture,buildingJsonFileUpdateTime,equipmentJsonFileUpdateTime,ruleJsonFileUpdateTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
//                executeResult = [db executeUpdate:sql, building.buildingId, building.buildingName, @(building.foundDate), building.contact, building.contactNumber, building.address, @(building.floorArea), @(building.buildingArea), building.coordinate, @(building.durableYears), building.surfacePicture, @(building.buildingJsonFileUpdateTime), @(building.equipmentJsonFileUpdateTime), @(building.ruleJsonFileUpdateTime)];
//            }
//            if (!executeResult) {
//                *stop = YES;
//                *rollback = YES;
//            };
//        }];
//        [db closeOpenResultSets];
//    }];
//    return executeResult;
//}

- (YWBuilding*)buildingWithSet:(FMResultSet*)set{
    YWBuilding* building = [[YWBuilding alloc] init];
    building.buildingId = [set stringForColumn:@"buildingId"];
    building.buildingName = [set stringForColumn:@"buildingName"];
    building.foundDate = [set longLongIntForColumn:@"foundDate"];
    building.contact = [set stringForColumn:@"contact"];
    building.contactNumber = [set stringForColumn:@"contactNumber"];
    building.address = [set stringForColumn:@"address"];
    building.floorArea = [set intForColumn:@"floorArea"];
    building.buildingArea = [set intForColumn:@"buildingArea"];
    building.coordinate = [set stringForColumn:@"coordinate"];
    building.durableYears = [set intForColumn:@"durableYears"];
    building.surfacePicture = [set stringForColumn:@"surfacePicture"];
    building.buildingJsonFileUpdateTime = [set longLongIntForColumn:@"buildingJsonFileUpdateTime"];
    building.equipmentJsonFileUpdateTime = [set longLongIntForColumn:@"equipmentJsonFileUpdateTime"];
    building.ruleJsonFileUpdateTime = [set longLongIntForColumn:@"ruleJsonFileUpdateTime"];
    return building;
}

- (YWBuilding*)buildingWithId:(NSString*)buildingId{
    __block YWBuilding* building = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'building' WHERE buildingId = ?;";
        FMResultSet* set = [db executeQuery:sql, buildingId];
        if ([set next]) {
            building = [self buildingWithSet:set];
        }
        [db closeOpenResultSets];
    }];
    return building;
}

- (NSArray*)allBuilding{
    __block NSMutableArray* buildings = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'building';";
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWBuilding* building = [self buildingWithSet:set];
            [buildings addObject:building];
        }
        [db closeOpenResultSets];
    }];
    return buildings.count ? buildings : nil;
}

- (YWBuilding*)buildingWithLocationId:(NSInteger)locationId{
    __block YWBuilding* building = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
//        NSString* sql = @"SELECT * FROM 'building' WHERE buildingId = (SELECT buildingId FROM 'apartment' WHERE apartmentId = (SELECT apartmentId FROM 'floor' WHERE floorId = (SELECT floorId FROM 'location' WHERE locationId = ?)));";
        NSString* sql = @"select b.* from location l left join floor f on f.floorId = l.floorId left join apartment a on a.apartmentId = f.apartmentId left join building b on b.buildingId = a.buildingId where l.locationId = ?";
        FMResultSet* set = [db executeQuery:sql, @(locationId)];
        if ([set next]) {
            building = [self buildingWithSet:set];
        }
        [db closeOpenResultSets];
    }];
    return building;
}

#pragma mark - apartment table

NSString *const KSqlCreateApartmentTable = @"CREATE TABLE IF NOT EXISTS 'apartment' (apartmentId integer NOT NULL UNIQUE,apartmentName varchar,code varchar,overgroundCount integer,undergroundCount integer,durableYears integer,buildingId varchar NOT NULL);";

- (BOOL)createApartmentTable{
    return [_fmdb executeUpdate:KSqlCreateApartmentTable];
}

- (void)dropAndReCreateApartmentTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists apartment;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateApartmentTable];
        }
    }];
}

- (BOOL)insertApartmentWithArray:(NSArray*)buildingJsonArray{
    __block BOOL executeResult = YES;
    __block NSArray* blockbuildingJsonArray = buildingJsonArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockbuildingJsonArray enumerateObjectsUsingBlock:^(YWBuildingJson* _Nonnull buildingJson, NSUInteger idx, BOOL* _Nonnull stop) {
            //apartmentId>=0是为了防止删掉离线录入报障的位置
            sql = @"DELETE FROM 'apartment' where buildingId=? AND apartmentId>=0;";
            executeResult = [db executeUpdate:sql, buildingJson.buildingId];
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
                executeResult = NO;
            }
            [buildingJson.apartments enumerateObjectsUsingBlock:^(YWApartmentJson* _Nonnull apartmentJson, NSUInteger idx, BOOL* _Nonnull stop) {
                NSString *sql = @"SELECT * FROM 'apartment' WHERE apartmentId=?;";
                FMResultSet* set = [db executeQuery:sql, @(apartmentJson.apartmentId)];
                if (![set next]) {
                    sql = @"INSERT INTO 'apartment' (apartmentId,apartmentName,code,overgroundCount,undergroundCount,durableYears,buildingId) VALUES (?,?,?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, @(apartmentJson.apartmentId), apartmentJson.apartmentName, apartmentJson.code, @(apartmentJson.overgroundCount), @(apartmentJson.undergroundCount), @(apartmentJson.durableYears), buildingJson.buildingId];
                }
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                };
            }];
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateApartmentWithArray:(NSArray*)ApartmentsArray{
    if (ApartmentsArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockApartmentsArray = ApartmentsArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockApartmentsArray enumerateObjectsUsingBlock:^(YWApartment* _Nonnull apartment, NSUInteger idx, BOOL* _Nonnull stop) {
            if (apartment.buildingId.length>0) {
                sql = @"SELECT * FROM 'apartment' WHERE apartmentId=?;";
                FMResultSet* set = [db executeQuery:sql, @(apartment.apartmentId)];
                if ([set next]) {
                    sql = @"UPDATE 'apartment' SET apartmentName=?,code=?,overgroundCount=?,undergroundCount=?,durableYears=?,buildingId=? WHERE apartmentId=?;";
                    executeResult = [db executeUpdate:sql, apartment.apartmentName, apartment.code, @(apartment.overgroundCount), @(apartment.undergroundCount), @(apartment.durableYears), apartment.buildingId, @(apartment.apartmentId)];
                }else {
                    sql = @"INSERT INTO 'apartment' (apartmentId,apartmentName,code,overgroundCount,undergroundCount,durableYears,buildingId) VALUES (?,?,?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, @(apartment.apartmentId), apartment.apartmentName, apartment.code, @(apartment.overgroundCount), @(apartment.undergroundCount), @(apartment.durableYears), apartment.buildingId];
                }
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                };
            }
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWApartment*)apartmentWithId:(NSInteger)apartmentId{
    __block YWApartment* apartment = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'apartment' WHERE apartmentId = ?;";
        FMResultSet* set = [db executeQuery:sql, @(apartmentId)];
        if ([set next]) {
            apartment = [self apartmentWithFMResultSet:set];
        }
        [db closeOpenResultSets];
    }];
    return apartment;
}

- (NSArray*)apartmentsWithbuildingId:(NSString*)buildingId{
    __block NSMutableArray* apartments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'apartment' WHERE buildingId =? AND apartmentId>0";
        FMResultSet* set = [db executeQuery:sql, buildingId];
        while ([set next]) {
            YWApartment* apartment = [self apartmentWithFMResultSet:set];
            [apartments addObject:apartment];
        }
        [db closeOpenResultSets];
    }];
    return apartments;
}

- (YWApartment*)apartmentWithFMResultSet:(FMResultSet*)set{
    YWApartment* apartment = [[YWApartment alloc] init];
    apartment.apartmentId = [set intForColumn:@"apartmentId"];
    apartment.apartmentName = [set stringForColumn:@"apartmentName"];
    apartment.code = [set stringForColumn:@"code"];
    apartment.overgroundCount = [set intForColumn:@"overgroundCount"];
    apartment.undergroundCount = [set intForColumn:@"undergroundCount"];
    apartment.durableYears = [set intForColumn:@"durableYears"];
    apartment.buildingId = [set stringForColumn:@"buildingId"];
    return apartment;
}

#pragma mark - floor table

NSString *const KSqlCreateFloorTable = @"CREATE TABLE IF NOT EXISTS 'floor' (floorId integer NOT NULL UNIQUE, floorName varchar, code varchar, height integer, apartmentId integer NOT NULL);";

- (BOOL)createFloorTable{
    return [_fmdb executeUpdate:KSqlCreateFloorTable];
}

- (void)dropAndReCreateFloorTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists floor;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateFloorTable];
        }
    }];
}

- (BOOL)insertFloorWithArray:(NSArray*)buildingJsonArray{
    __block BOOL executeResult = YES;
    __block NSArray* blockbuildingJsonArray = buildingJsonArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockbuildingJsonArray enumerateObjectsUsingBlock:^(YWBuildingJson* _Nonnull buildingJson, NSUInteger idx, BOOL* _Nonnull stop) {
            [buildingJson.apartments enumerateObjectsUsingBlock:^(YWApartmentJson* _Nonnull apartmentJson, NSUInteger idx, BOOL* _Nonnull stop) {
                //floorId>=0是为了防止删掉离线录入报障的位置
                sql = @"DELETE FROM 'floor' WHERE apartmentId=? AND floorId>=0;";
                executeResult = [db executeUpdate:sql, @(apartmentJson.apartmentId)];
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                    executeResult = NO;
                }
                [apartmentJson.floors enumerateObjectsUsingBlock:^(YWFloorJson* _Nonnull floorJson, NSUInteger idx, BOOL* _Nonnull stop) {
                    NSString *sql = @"SELECT * FROM 'floor' WHERE floorId=?;";
                    FMResultSet* set = [db executeQuery:sql, @(floorJson.floorId)];
                    if (![set next]) {
                        sql = @"INSERT INTO 'floor' (floorId,floorName,code,height,apartmentId) VALUES (?,?,?,?,?);";
                        executeResult = [db executeUpdate:sql, @(floorJson.floorId), floorJson.floorName, floorJson.code, @(floorJson.height), @(apartmentJson.apartmentId)];
                    }
                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    };
                }];
            }];
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateFloorWithArray:(NSArray*)FloorsArray{
    if (FloorsArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockFloorsArray = FloorsArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockFloorsArray enumerateObjectsUsingBlock:^(YWFloor* _Nonnull floor, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'floor' WHERE floorId=?;";
            FMResultSet* set = [db executeQuery:sql, @(floor.floorId)];
            if ([set next]) {
                sql = @"UPDATE 'floor' SET floorName=?,code=?,height=?,apartmentId=? WHERE floorId=?;";
                executeResult = [db executeUpdate:sql, floor.floorName, floor.code, @(floor.height), @(floor.apartmentId), @(floor.floorId)];
            }else {
                sql = @"INSERT INTO 'floor' (floorId,floorName,code,height,apartmentId) VALUES (?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, @(floor.floorId), floor.floorName, floor.code, @(floor.height), @(floor.apartmentId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWFloor*)floorWithId:(NSInteger)floorId{
    __block YWFloor* floor = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'floor' WHERE floorId = ?;";
        FMResultSet* set = [db executeQuery:sql, @(floorId)];
        while ([set next]) {
            floor = [self floorWithFMResultSet:set];
        }
        [db closeOpenResultSets];
    }];
    return floor;
}

- (NSArray*)floorsWithApartmentId:(NSInteger)apartmentId{
    __block NSMutableArray* floors = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'floor' WHERE apartmentId =? AND floorId>0";
        FMResultSet* set = [db executeQuery:sql, @(apartmentId)];
        while ([set next]) {
            YWFloor* floor = [self floorWithFMResultSet:set];
            [floors addObject:floor];
        }
        [db closeOpenResultSets];
    }];
    return floors;
}

- (YWFloor*)floorWithFMResultSet:(FMResultSet*)set{
    YWFloor* floor = [[YWFloor alloc] init];
    floor.floorId = [set intForColumn:@"floorId"];
    floor.floorName = [set stringForColumn:@"floorName"];
    floor.code = [set stringForColumn:@"code"];
    floor.height = [set intForColumn:@"height"];
    floor.apartmentId = [set intForColumn:@"apartmentId"];
    return floor;
}

#pragma mark - location table

NSString *const KSqlCreateLocationTable = @"CREATE TABLE IF NOT EXISTS 'location' (locationId integer NOT NULL UNIQUE, locationName varchar, code varchar, floorId integer NOT NULL);";

- (BOOL)createLocationTable{
    return [_fmdb executeUpdate:KSqlCreateLocationTable];
}

- (void)dropAndReCreateLocationTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists location;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateLocationTable];
        }
    }];
}

- (BOOL)insertLocationWithArray:(NSArray*)buildingJsonArray
{
    __block BOOL executeResult = YES;
    __block NSArray* blockbuildingJsonArray = buildingJsonArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {

        [blockbuildingJsonArray enumerateObjectsUsingBlock:^(YWBuildingJson* _Nonnull buildingJson, NSUInteger idx, BOOL* _Nonnull stop) {

            [buildingJson.apartments enumerateObjectsUsingBlock:^(YWApartmentJson* _Nonnull apartmentJson, NSUInteger idx, BOOL* _Nonnull stop) {

                [apartmentJson.floors enumerateObjectsUsingBlock:^(YWFloorJson* _Nonnull floorJson, NSUInteger idx, BOOL* _Nonnull stop) {
                    //locationId>=0是为了防止删掉离线录入报障的位置
                    sql = @"DELETE FROM 'location' WHERE floorId=? AND locationId>=0;";
                    executeResult = [db executeUpdate:sql, @(floorJson.floorId)];
                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                        executeResult = NO;
                    }
                    [floorJson.locations enumerateObjectsUsingBlock:^(YWLocationJson* _Nonnull locationJson, NSUInteger idx, BOOL* _Nonnull stop) {
                        NSString *sql = @"SELECT * FROM 'location' WHERE locationId=?;";
                        FMResultSet* set = [db executeQuery:sql, @(locationJson.locationId)];
                        if (![set next]) {
                            sql = @"INSERT INTO 'location' (locationId, locationName , code , floorId ) VALUES (?,?,?,?);";
                            executeResult = [db executeUpdate:sql, @(locationJson.locationId), locationJson.locationName, locationJson.code, @(floorJson.floorId)];
                        }
                        if (!executeResult) {
                            *stop = YES;
                            *rollback = YES;
                        };
                    }];
                }];
            }];
        }];
        [db closeOpenResultSets];
    }];
    //    //保存位置和二维码关联
    //    [self saveLocationQrcodeRelWithLocationJson:locationAndQrcodeRelArray];
    return executeResult;
}

//- (BOOL)saveLocationQrcodeRelWithLocationJson:(NSArray*)locationJson{
//    __block BOOL executeResult = YES;
//    __block NSArray* blockLocationJson = locationJson;
//    __block NSString* sql = nil;
//    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
//        [blockLocationJson enumerateObjectsUsingBlock:^(YWLocationJson* _Nonnull locationJson, NSUInteger idx, BOOL* _Nonnull stop) {
//
//            [locationJson.qrcodes enumerateObjectsUsingBlock:^(qrcodeJson* _Nonnull qrcode, NSUInteger idx, BOOL* _Nonnull stop) {
////                if ([qrcode.qrcodeId isEqualToString:@"000001000270-3264-1"]) {
////                    YWLog(@"%@---%@---%@",@(locationJson.locationId), qrcode.qrcodeId,locationJson.locationName);
////                }
//                sql = @"SELECT * FROM 'location_qrcode_rel' WHERE qrcodeId=?;";
//                FMResultSet* set = [db executeQuery:sql, qrcode.qrcodeId];
//
//                if ([set next]) {
//                    sql = @"UPDATE 'location_qrcode_rel' SET locationId=? WHERE qrcodeId=?;";
//                    executeResult = [db executeUpdate:sql, @(locationJson.locationId), qrcode.qrcodeId];
//                }
//                else {
//                    sql = @"INSERT INTO 'location_qrcode_rel' (locationId, qrcodeId) VALUES (?,?);";
//                    executeResult = [db executeUpdate:sql, @(locationJson.locationId), qrcode.qrcodeId];
//                }
//                if (!executeResult) {
//                    *stop = YES;
//                    *rollback = YES;
//                };
//            }];
//        }];
//
//        [db closeOpenResultSets];
//    }];
//    return executeResult;
//}

- (BOOL)updateLocationWithArray:(NSArray*)locationsArray{
    if (locationsArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockLocationsArray = locationsArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockLocationsArray enumerateObjectsUsingBlock:^(YWLocation* _Nonnull location, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'location' WHERE locationId=?;";
            FMResultSet* set = [db executeQuery:sql, @(location.locationId)];
            if ([set next]) {
                sql = @"UPDATE 'location' SET locationName=?, code=?, floorId=? WHERE locationId=?;";
                executeResult = [db executeUpdate:sql, location.locationName, location.code, @(location.floorId), @(location.locationId)];
            }else {
                sql = @"INSERT INTO 'location' (locationId, locationName , code , floorId ) VALUES (?,?,?,?);";
                executeResult = [db executeUpdate:sql, @(location.locationId), location.locationName, location.code, @(location.floorId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWLocation*)locationWithId:(NSInteger)locationId
{
    __block YWLocation* location = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'location' WHERE locationId = ?;";
        FMResultSet* set = [db executeQuery:sql, @(locationId)];
        if ([set next]) {
            location = [self locationWithFMResultSet:set];
        }
        [db closeOpenResultSets];
    }];
    return location;
}

- (NSArray*)locationsWithFloorId:(NSInteger)floorId
{
    __block NSMutableArray* locations = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'location' WHERE floorId =? AND locationId>0 GROUP BY locationId;";
        FMResultSet* set = [db executeQuery:sql, @(floorId)];
        while ([set next]) {
            YWLocation*location = [self locationWithFMResultSet:set];
            [locations addObject:location];
        }
        [db closeOpenResultSets];
    }];
    return locations;
}

- (NSArray *)locationWithBuildingId:(NSString *)buildingId apartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId page:(NSInteger)page{
    __block NSMutableArray* locations = [NSMutableArray array];
    __block NSInteger showCount = page * 20;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (floorId>0) {
            sql = @"SELECT * FROM 'location' WHERE floorId = ? AND locationId>0 GROUP BY locationId LIMIT ?";
            set = [db executeQuery:sql, @(floorId),@(showCount)];
        }else if (apartmentId>0){
            sql = @"select l.* from 'location' l LEFT join 'floor' f on l.floorId=f.floorId LEFT join 'apartment' a on f.apartmentId=a.apartmentId where a.apartmentId=? AND l.locationId>0 GROUP BY l.locationId LIMIT ?";
            set = [db executeQuery:sql, @(apartmentId),@(showCount)];
        }else if (buildingId.length>0){
            sql = @"select l.* from 'location' l LEFT join 'floor' f on l.floorId=f.floorId LEFT join 'apartment' a on f.apartmentId=a.apartmentId LEFT join 'building' b on b.buildingId=a.buildingId where b.buildingId=? AND l.locationId>0 GROUP BY l.locationId LIMIT ?";
            set = [db executeQuery:sql, buildingId,@(showCount)];
        }
        while ([set next]) {
            YWLocation*location = [self locationWithFMResultSet:set];
            [locations addObject:location];
        }
        [db closeOpenResultSets];
    }];
    return locations;
}

- (NSArray *)buildingArrayWithLineId:(NSInteger)lineId type:(BOOL)isKeepWatch lineType:(BOOL)isEquipmentLine{
    if (lineId <= 0) {
        return nil;
    }
    __block NSMutableArray* buildingArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (isKeepWatch) {
            //巡更
            sql = @"select distinct b.* from 'building' b LEFT join 'apartment' a on b.buildingId=a.buildingId LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'patrolline_location_rel' p on l.locationId=p.locationId WHERE p.patrolLineId=?";
            set = [db executeQuery:sql,@(lineId)];
        }else{
            if (isEquipmentLine) {
                //设备巡查
                sql = @"select distinct b.* from 'building' b LEFT join 'apartment' a on b.buildingId=a.buildingId LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'inspectionLine_equipment_rel' i on e.equipmentId=i.equipmentId WHERE i.inspectionLineId=?";
                set = [db executeQuery:sql,@(lineId)];
            }else{
                //综合巡查
                sql = @"select distinct b.* from 'building' b LEFT join 'apartment' a on b.buildingId=a.buildingId LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'inspectionLine_location_rel' i on l.locationId=i.locationId WHERE i.inspectionLineId=?";
                set = [db executeQuery:sql,@(lineId)];
            }
        }
        while ([set next]) {
            YWBuilding *building = [self buildingWithSet:set];
            [buildingArray addObject:building];
        }
        [db closeOpenResultSets];
    }];
    return buildingArray;
}

- (NSArray *)apartmentArrayWithBuildingId:(NSString*)buildingId LineId:(NSInteger)lineId type:(BOOL)isKeepWatch lineType:(BOOL)isEquipmentLine{
    if (lineId <= 0 || buildingId.length==0) {
        return nil;
    }
    __block NSMutableArray* apartmentArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (isKeepWatch) {
            //巡更
            sql = @"select distinct a.* from 'apartment' a LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'patrolline_location_rel' p on l.locationId=p.locationId WHERE p.patrolLineId=? AND a.buildingId=? AND a.apartmentId>0";
            set = [db executeQuery:sql,@(lineId),buildingId];
        }else{
            if (isEquipmentLine) {
                //设备巡查
                sql = @"select distinct a.* from 'apartment' a LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'inspectionLine_equipment_rel' i on e.equipmentId=i.equipmentId WHERE i.inspectionLineId=? AND a.buildingId=? AND a.apartmentId>0";
                set = [db executeQuery:sql,@(lineId),buildingId];
            }else{
                //综合巡查
                sql = @"select distinct a.* from 'apartment' a LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'inspectionLine_location_rel' i on l.locationId=i.locationId WHERE i.inspectionLineId=? AND a.buildingId=? AND a.apartmentId>0";
                set = [db executeQuery:sql,@(lineId),buildingId];
            }
        }
        while ([set next]) {
            YWApartment *apartment = [self apartmentWithFMResultSet:set];
            [apartmentArray addObject:apartment];
        }
        [db closeOpenResultSets];
    }];
    return apartmentArray;
}

- (NSArray *)floorArrayWithApartmentId:(NSInteger)apartmentId LineId:(NSInteger)lineId type:(BOOL)isKeepWatch lineType:(BOOL)isEquipmentLine{
    if (lineId <= 0 || apartmentId <= 0) {
        return nil;
    }
    __block NSMutableArray* floorArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (isKeepWatch) {
            //巡更
            sql = @"select distinct f.* from 'floor' f LEFT join 'location' l on l.floorId=f.floorId LEFT join 'patrolline_location_rel' p on l.locationId=p.locationId WHERE p.patrolLineId=? AND f.apartmentId=? AND f.floorId>0";
            set = [db executeQuery:sql,@(lineId),@(apartmentId)];
        }else{
            if (isEquipmentLine) {
                //设备巡查
                sql = @"select distinct f.* from 'floor' f LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'inspectionLine_equipment_rel' i on e.equipmentId=i.equipmentId WHERE i.inspectionLineId=? AND f.apartmentId=? AND f.floorId>0";
                set = [db executeQuery:sql,@(lineId),@(apartmentId)];
            }else{
                //综合巡查
                sql = @"select distinct f.* from 'floor' f LEFT join 'location' l on l.floorId=f.floorId LEFT join 'inspectionLine_location_rel' i on l.locationId=i.locationId WHERE i.inspectionLineId=? AND f.apartmentId=? AND f.floorId>0";
                set = [db executeQuery:sql,@(lineId),@(apartmentId)];
            }
        }
        while ([set next]) {
            YWFloor *floor = [self floorWithFMResultSet:set];
            [floorArray addObject:floor];
        }
        [db closeOpenResultSets];
    }];
    return floorArray;
}

- (NSArray *)locationArrayWithfloorId:(NSInteger)floorId LineId:(NSInteger)lineId type:(BOOL)isKeepWatch lineType:(BOOL)isEquipmentLine{
    if (lineId <= 0 || floorId <= 0) {
        return nil;
    }
    __block NSMutableArray* locationArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (isKeepWatch) {
            //巡更
            sql = @"select distinct l.* from 'location' l LEFT join 'patrolline_location_rel' p on l.locationId=p.locationId WHERE p.patrolLineId=? AND l.floorId=? AND l.locationId>0";
            set = [db executeQuery:sql,@(lineId),@(floorId)];
        }else{
            if (isEquipmentLine) {
                //设备巡查
                sql = @"select distinct l.* from 'location' l LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'inspectionLine_equipment_rel' i on e.equipmentId=i.equipmentId WHERE i.inspectionLineId=? AND l.floorId=? AND l.locationId>0";
                set = [db executeQuery:sql,@(lineId),@(floorId)];
            }else{
                //综合巡查
                sql = @"select distinct l.* from 'location' l LEFT join 'inspectionLine_location_rel' i on l.locationId=i.locationId WHERE i.inspectionLineId=? AND l.floorId=? AND l.locationId>0";
                set = [db executeQuery:sql,@(lineId),@(floorId)];
            }
        }
        while ([set next]) {
            YWLocation *location = [self locationWithFMResultSet:set];
            [locationArray addObject:location];
        }
        [db closeOpenResultSets];
    }];
    return locationArray;
}

- (NSArray *)selectPositionWithMissionId:(NSInteger)missionId equipmentTypeId:(NSInteger)equipmentTypeId positionType:(NSInteger)positionType buildingId:(NSString *)buildingId apartmentId:(NSInteger)apartmentId floorId:(NSInteger)floorId{
    if (missionId <= 0 || equipmentTypeId <= 0) {
        return nil;
    }
    //---1:楼盘/2:楼栋/3:楼层/4:位置
    __block NSMutableArray* positionArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        BOOL isEquipemnt = NO;//是否是指定设备
        NSString *sql = @"SELECT equipmentId FROM 'mission_maintenance_equipment' where missionId=?";
        FMResultSet *set = [db executeQuery:sql,@(missionId)];
        if ([set next]) {isEquipemnt = YES;}
        if (positionType == 1) {
            if (isEquipemnt) {
                sql = @"select distinct b.* from 'building' b LEFT join 'apartment' a on b.buildingId=a.buildingId LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance_equipment' i on e.equipmentId=i.equipmentId WHERE i.missionId=?";
                set = [db executeQuery:sql,@(missionId)];
            }else{
                sql = @"select distinct b.* from 'building' b LEFT join 'apartment' a on b.buildingId=a.buildingId LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance' i on e.equipmentTypeId=i.equipmentTypeId WHERE i.missionId=?";
                set = [db executeQuery:sql,@(missionId)];
            }
            while ([set next]) {
                YWBuilding *building = [self buildingWithSet:set];
                [positionArray addObject:building];
            }
        }else if (positionType == 2){
            if (isEquipemnt) {
                sql = @"select distinct a.* from 'apartment' a LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance_equipment' i on e.equipmentId=i.equipmentId WHERE i.missionId=? AND a.buildingId=?";
                set = [db executeQuery:sql,@(missionId),buildingId];
            }else{
                sql = @"select distinct a.* from 'apartment' a LEFT join 'floor' f on f.apartmentId=a.apartmentId LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance' i on e.equipmentTypeId=i.equipmentTypeId WHERE i.missionId=? AND a.buildingId=?";
                set = [db executeQuery:sql,@(missionId),buildingId];
            }
            while ([set next]) {
                YWApartment *apartment = [self apartmentWithFMResultSet:set];
                [positionArray addObject:apartment];
            }
        }else if (positionType == 3){
            if (isEquipemnt) {
                sql = @"select distinct f.* from 'floor' f LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance_equipment' i on e.equipmentId=i.equipmentId WHERE i.missionId=? AND f.apartmentId=?";
                set = [db executeQuery:sql,@(missionId),@(apartmentId)];
            }else{
                sql = @"select distinct f.* from 'floor' f LEFT join 'location' l on l.floorId=f.floorId LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance' i on e.equipmentTypeId=i.equipmentTypeId WHERE i.missionId=? AND f.apartmentId=?";
                set = [db executeQuery:sql,@(missionId),@(apartmentId)];
            }
            while ([set next]) {
                YWFloor *floor = [self floorWithFMResultSet:set];
                [positionArray addObject:floor];
            }
        }else if (positionType == 4){
            if (isEquipemnt) {
                sql = @"select distinct l.* from 'location' l LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance_equipment' i on e.equipmentId=i.equipmentId WHERE i.missionId=? AND l.floorId=?";
                set = [db executeQuery:sql,@(missionId),@(floorId)];
            }else{
                sql = @"select distinct l.* from 'location' l LEFT join 'equipment' e on l.locationId=e.locationId LEFT join 'mission_maintenance' i on e.equipmentTypeId=i.equipmentTypeId WHERE i.missionId=? AND l.floorId=?";
                set = [db executeQuery:sql,@(missionId),@(floorId)];
            }
            while ([set next]) {
                YWLocation *location = [self locationWithFMResultSet:set];
                [positionArray addObject:location];
            }
        }
        [db closeOpenResultSets];
    }];
    return positionArray;
}

- (YWLocation*)locationWithFMResultSet:(FMResultSet*)set{
    YWLocation* location = [[YWLocation alloc] init];
    location.locationId = [set intForColumn:@"locationId"];
    location.locationName = [set stringForColumn:@"locationName"];
    location.code = [set stringForColumn:@"code"];
    location.floorId = [set intForColumn:@"floorId"];
    return location;
}


#pragma mark - picture table
/**
 *  名称	图片表 picture
 */
- (BOOL)createPictureTable
{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'picture' (pictureId varchar(30),pictureName varchar(50),bigPictureUrl varchar(300),smallPictureUrl varchar(300),isLocalImage boolean DEFAULT 0,uploadStatus smallint DEFAULT 0,missionId integer NOT NULL,maintenanceType smallint NOT NULL,equipmentId varchar(24),pictureTroubleType smallint DEFAULT 0,recordId integer);";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)updatePictureWithArray:(NSArray*)pictures
{
    if (pictures.count==0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockPictures = pictures;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {

        [blockPictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {

            sql = @"SELECT * FROM 'picture' WHERE pictureId=?;";
            FMResultSet* set = [db executeQuery:sql, picture.pictureId];

            if ([set next]) {
                sql = @"UPDATE 'picture' SET pictureName =?,bigPictureUrl=?,smallPictureUrl =?,isLocalImage =?,uploadStatus=?,missionId=?,maintenanceType=?,equipmentId=?,recordId=? WHERE pictureId=?;";
                executeResult = [db executeUpdate:sql, picture.pictureName, picture.bigPictureUrl, picture.smallPictureUrl, @(picture.isLocalImage), @(picture.uploadStatus), @(picture.missionId), @(picture.maintenanceType), picture.equipmentId, @(picture.recordId), picture.pictureId];
            }
            else {
                sql = @"INSERT INTO 'picture' (pictureId,pictureName,bigPictureUrl,smallPictureUrl,isLocalImage,uploadStatus,missionId,maintenanceType,equipmentId,pictureTroubleType,recordId) VALUES (?, ?, ?, ?, ?, ?, ?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, picture.pictureId, picture.pictureName, picture.bigPictureUrl, picture.smallPictureUrl, @(picture.isLocalImage), @(picture.uploadStatus), @(picture.missionId), @(picture.maintenanceType), picture.equipmentId, @(picture.pictureTroubleType), @(picture.recordId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWPicture*)pictureWithFMResultSet:(FMResultSet*)set
{
    YWPicture* picture = [[YWPicture alloc] init];
    picture.pictureId = [set stringForColumn:@"pictureId"];
    picture.pictureName = [set stringForColumn:@"pictureName"];
    picture.bigPictureUrl = [set stringForColumn:@"bigPictureUrl"];
    picture.smallPictureUrl = [set stringForColumn:@"smallPictureUrl"];
    picture.isLocalImage = [set boolForColumn:@"isLocalImage"];
    picture.uploadStatus = [set intForColumn:@"uploadStatus"];
    picture.missionId = [set intForColumn:@"missionId"];
    picture.maintenanceType = [set intForColumn:@"maintenanceType"];
    picture.equipmentId = [set stringForColumn:@"equipmentId"];
    picture.pictureTroubleType = [set intForColumn:@"pictureTroubleType"];
    picture.recordId = [[NSString stringWithFormat:@"%@", [set objectForColumnName:@"recordId"]] longLongValue];
    return picture;
}

- (NSArray*)troublePicturesWithRecordId:(NSInteger)recordId pictureTroubleType:(YWPictureTroubleType)type
{
    __block NSMutableArray* pictures = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'picture' WHERE recordId=? AND maintenanceType=? AND pictureTroubleType = ?";
        FMResultSet* set = [db executeQuery:sql, @(recordId), @(YWMaintenanceTypeTrouble), @(type)];

        while ([set next]) {
            YWPicture* picture = [self pictureWithFMResultSet:set];
            [pictures addObject:picture];
        }
        [db closeOpenResultSets];
    }];
    return pictures;
}
- (NSArray*)picturesWithTroubleMissionId:(NSInteger)missionId pictureTroubleType:(YWPictureTroubleType)type
{
    __block NSMutableArray* pictures = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'picture' WHERE missionId=? AND maintenanceType=? AND pictureTroubleType = ?";
        FMResultSet* set = [db executeQuery:sql, @(missionId), @(YWMaintenanceTypeTrouble), @(type)];

        while ([set next]) {
            YWPicture* picture = [self pictureWithFMResultSet:set];
            [pictures addObject:picture];
        }
        [db closeOpenResultSets];
    }];
    return pictures;
}
- (NSArray*)picturesWithMissionId:(NSInteger)missionId maintenanceType:(YWMaintenanceType)maintenanceType
{
    __block NSMutableArray* pictures = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'picture' WHERE missionId=? AND maintenanceType=?";
        FMResultSet* set = [db executeQuery:sql, @(missionId), @(maintenanceType)];

        while ([set next]) {
            YWPicture* picture = [self pictureWithFMResultSet:set];
            [pictures addObject:picture];
        }
        [db closeOpenResultSets];
    }];
    return pictures;
}

- (NSArray*)picturesWithEquipmentId:(NSString*)equipmentId pictureTroubleType:(YWPictureTroubleType)type
{
    __block NSMutableArray* pictures = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'picture' WHERE equipmentId = ? AND pictureTroubleType = ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId,@(type)];

        while ([set next]) {
            YWPicture* picture = [self pictureWithFMResultSet:set];
            [pictures addObject:picture];
        }
        [db closeOpenResultSets];
    }];
    return pictures;
}

- (NSArray*)picturesWithRecordId:(NSInteger)recordId maintenanceType:(NSInteger)maintenanceTypeId
{
    __block NSMutableArray* pictures = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'picture' WHERE recordId=? AND maintenanceType=?";
        FMResultSet* set = [db executeQuery:sql, @(recordId), @(maintenanceTypeId)];

        while ([set next]) {
            YWPicture* picture = [self pictureWithFMResultSet:set];
            [pictures addObject:picture];
        }
        [db closeOpenResultSets];
    }];
    return pictures;
}

///**
// *  名称	任务表 mission
// */
//- (BOOL)createMissionTable
//{
//    NSString* sql = @"CREATE TABLE 'mission' (missionId integer NOT NULL,missionName varchar(100),maintenanceTypeId integer NOT NULL,equipmentId varchar(24),equipmentTypeId integer DEFAULT 0,startTime timestamp,cutoffTime date,missionStatus smallint,status smallint NOT NULL,createTime timestamp,updateTime timestamp,missionType smallint NOT NULL DEFAULT 0,equipmentQuantity integer  DEFAULT 0,completedQuantity integer  DEFAULT 0,finishTime timestamp,reporterId integer, reporterName varchar,reporterNumber varchar,note varchar,reportTime timestamp,uploadFail boolean DEFAULT 0,qrcodeId varchar(100),pendingHandlerName varchar(100),executorId integer,executorIds text,creatorId integer,demand varchar(100),read boolean DEFAULT 0,buildingId varchar (13));";
//    return [_fmdb executeUpdate:sql];
//}

//#pragma mark - 维修任务表
//NSString *const KSqlCreateTroubleMissionTable = @"CREATE TABLE IF NOT EXISTS 'mission_trouble' (troubleId integer NOT NULL,troubleSequence varchar,maintenanceTypeId integer NOT NULL,equipmentId varchar(24),equipmentTypeId integer DEFAULT 0,cutoffTime timestamp,createTime timestamp,updateTime timestamp,troubleStatus smallint NOT NULL,note varchar,cancelNote varchar,reportTime timestamp,uploadFail boolean DEFAULT 0,qrcodeId varchar,finishTime timestamp,read boolean DEFAULT 0,buildingId varchar,demand varchar,executorId integer,creatorId integer,reporterId integer,isPostTrouble boolean DEFAULT 0,uniqueTag varchar,channel smallint,locationId integer,observerIds varchar,troubleMissionType smallint);";
//


- (BOOL)updateMissionHanler:(YWHandler*)handler set:(FMResultSet*)set db:(FMDatabase*)db
{
    BOOL executeResult = YES;
    if (handler.uniqueId == 0)
        return YES;
    NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId=?;";
    set = [db executeQuery:sql, @(handler.uniqueId)];
    if ([set next]) {
        if (handler.userName.length>0 && handler.headIcon.length>0 && handler.mobile.length>0) {
            NSString *newSql = sql = @"UPDATE 'handler' SET userName=?,headIcon=?,mobile=? WHERE uniqueId=?;";
            executeResult = [db executeUpdate:newSql, handler.userName, handler.headIcon, handler.mobile, @(handler.uniqueId)];
        }else if (handler.userName.length>0 && handler.headIcon.length>0){
            NSString *newSql = sql = @"UPDATE 'handler' SET userName=?,headIcon=? WHERE uniqueId=?;";
            executeResult = [db executeUpdate:newSql, handler.userName, handler.headIcon, @(handler.uniqueId)];
        }else if (handler.userName.length>0){
            NSString *newSql = sql = @"UPDATE 'handler' SET userName=? WHERE uniqueId=?;";
            executeResult = [db executeUpdate:newSql, handler.userName,@(handler.uniqueId)];
        }
    }else {
        sql = @"INSERT INTO 'handler' (uniqueId,userName,headIcon,mobile) VALUES (?, ?, ?, ?);";
        executeResult = [db executeUpdate:sql, @(handler.uniqueId), handler.userName, handler.headIcon, handler.mobile];
    }

    return executeResult;
}


- (BOOL)updatePostTroubleId:(YWReportTroubleModel *)reportTrouble uniqueTag:(NSString *)uniqueTag{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'YW_ReportTrouble' SET troubleId=?,troubleSequence=?,troubleStatus=?,uploadFail=0 WHERE uniqueTag=?;";
        executeResult = [db executeUpdate:sql, @(reportTrouble.troubleId),reportTrouble.troubleSequence,@(reportTrouble.troubleStatus), uniqueTag];
        [db closeOpenResultSets];
    }];
    return executeResult;
}


- (NSArray*)unfinishedMissionsWithQrcodeID:(NSString*)qrcodeID orLocationId:(NSInteger)locationId
{
    __block NSMutableArray* unfinisheMissions = [NSMutableArray array];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        NSMutableString* equipmentIds = [NSMutableString string];
//        NSMutableString* equipmentFloorIds = [NSMutableString string];
//        NSMutableString* equipmentApartmentIds = [NSMutableString string];
        NSMutableString* equipmentTypeIds = [NSMutableString string];
        NSString *buildingId = nil;
        if (qrcodeID) {
            //先查buidlingid，匹配检测保养的时候用
            sql = [NSString stringWithFormat:@"select buildingId from 'equipment' where qrcodeId = ?"];
            set = [db executeQuery:sql, qrcodeID];
            if ([set next]) {
                buildingId = [set stringForColumn:@"buildingId"];
            }
            
            sql = [NSString stringWithFormat:@"SELECT * FROM 'equipment' WHERE qrcodeId = ?;"];
            set = [db executeQuery:sql, qrcodeID];
        }else if (locationId){
            //先查buidlingid，匹配检测保养的时候用
            sql = [NSString stringWithFormat:@"select buildingId from 'equipment' where locationId = ?"];
            set = [db executeQuery:sql, @(locationId)];
            if ([set next]) {
                buildingId = [set stringForColumn:@"buildingId"];
            }
            
            sql = [NSString stringWithFormat:@"SELECT * FROM 'equipment' WHERE locationId = ?;"];
            set = [db executeQuery:sql, @(locationId)];
        }
        
        NSInteger index = 0;
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            if (equipment) {
                if (index == 0) {
                    [equipmentIds appendString:@"("];
//                    [equipmentFloorIds appendString:@"("];
//                    [equipmentApartmentIds appendString:@"("];
                    [equipmentTypeIds appendString:@"("];
                }
                else {
                    [equipmentIds appendString:@","];
//                    [equipmentFloorIds appendString:@","];
//                    [equipmentApartmentIds appendString:@","];
                    [equipmentTypeIds appendString:@","];
                }
                [equipmentIds appendString:[NSString stringWithFormat:@"'%@'", equipment.equipmentId]];
//                [equipmentFloorIds appendString:[NSString stringWithFormat:@"%ld", (long)equipment.floorId]];
//                [equipmentApartmentIds appendString:[NSString stringWithFormat:@"%ld", (long)equipment.apartmentId]];
                [equipmentTypeIds appendString:[NSString stringWithFormat:@"%ld", (long)equipment.equipmentTypeId]];
                index++;
            }
        }
        if (equipmentIds.length > 0) {
            [equipmentIds appendString:@")"];
//            [equipmentFloorIds appendString:@")"];
//            [equipmentApartmentIds appendString:@")"];
            [equipmentTypeIds appendString:@")"];
        }
        YWLoginUser* currentUser = [YWLoginTool loginUser];
        //维修任务（维保任务是没有equipmentId）
        if (qrcodeID) {
            if (equipmentIds.length) {
//                sql = [NSString stringWithFormat:@"SELECT * FROM mission_trouble where troubleStatus = ? and executorId = ? and qrcodeId=? and equipmentId in %@", equipmentIds];
                sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' where troubleStatus = ? and executorId = ? and troubleId in (SELECT troubleId FROM 'YW_ReportTrouble' where qrcodeId=? and equipmentId in %@)", equipmentIds];
                
                set = [db executeQuery:sql, @(YWTroubleMissionStatusAssign),@(currentUser.uniqueId),qrcodeID];
            }else{
                set = nil;
            }
        }else if (locationId){
//            sql = [NSString stringWithFormat:@"SELECT * FROM mission_trouble where troubleStatus = ? and executorId = ? and locationId=?"];
            sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' where troubleStatus = ? and executorId = ? and troubleId in (SELECT troubleId FROM 'YW_ReportTrouble' where locationId=?)"];
            set = [db executeQuery:sql, @(YWTroubleMissionStatusAssign),@(currentUser.uniqueId),@(locationId)];
        }
        while ([set next]) {
//            YWTroubleMission* troubleMission = [self troubleMissionWithFMResultSet:set FMDatabase:db];
//            [unfinisheMissions addObject:troubleMission];
            YWTroubleMissionModel * troubleMissionModel = [[YWTroubleMissionDBManager shareManager] troubleMissionModelWithFMResultSet:set FMDatabase:db needSelectReportTrouble:YES];
            [unfinisheMissions addObject:troubleMissionModel];
        }
        
        if (equipmentTypeIds.length) {
            sql = [NSString stringWithFormat:@"select * from mission_maintenance where equipmentTypeId in %@ AND missionStatus = %lu AND maintenanceTypeId !=%ld AND buildingId ='%@' AND status=0", equipmentTypeIds,(unsigned long)YWMissionStatusUnfinished,(unsigned long)YWMaintenanceTypeTrouble,buildingId];
            set = [db executeQuery:sql];
        }else{
            set = nil;
        }
        while ([set next]) {
            YWMaintenanceMission* maintenanceMission = [YWDetectAndUpkeepDBManager maintenanceMissionWithFMResultSet:set FMDatabase:db];
            if ([maintenanceMission.executorIds rangeOfString:[@(currentUser.uniqueId) stringValue]].location != NSNotFound) {
                if (maintenanceMission.equipments.count>0) {
                    [unfinisheMissions addObject:maintenanceMission];
                }else{
                    [unfinisheMissions addObject:maintenanceMission];
                }
            }
        }

        [db closeOpenResultSets];
    }];
    return unfinisheMissions;
}

- (NSArray*)unfinishedMissionsWithQrcodeID:(NSString*)qrcodeID orLocationId:(NSInteger)locationId andMaintenanceTypeId:(NSInteger)maintenanceTypeId
{
    __block NSMutableArray* unfinishedMissions = [NSMutableArray array];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        NSMutableString* equipmentIds = [NSMutableString string];
//        NSMutableString* equipmentFloorIds = [NSMutableString string];
//        NSMutableString* equipmentApartmentIds = [NSMutableString string];
        NSMutableString* equipmentTypeIds = [NSMutableString string];
        NSString *buildingId = nil;
        if (qrcodeID) {
            if (maintenanceTypeId == YWMaintenanceTypeDetection || maintenanceTypeId == YWMaintenanceTypeUpkeep) {
                //先查buidlingid，匹配检测保养的时候用
                sql = [NSString stringWithFormat:@"select buildingId from 'equipment' where qrcodeId = ?"];
                set = [db executeQuery:sql, qrcodeID];
                if ([set next]) {
                    buildingId = [set stringForColumn:@"buildingId"];
                }
            }
            
            sql = [NSString stringWithFormat:@"SELECT * FROM 'equipment' WHERE qrcodeId = ?;"];
            set = [db executeQuery:sql, qrcodeID];
        }else if (locationId){
            if (maintenanceTypeId == YWMaintenanceTypeDetection || maintenanceTypeId == YWMaintenanceTypeUpkeep) {
                //先查buidlingid，匹配检测保养的时候用
                sql = [NSString stringWithFormat:@"select buildingId from 'equipment' where locationId = ?"];
                set = [db executeQuery:sql, @(locationId)];
                if ([set next]) {
                    buildingId = [set stringForColumn:@"buildingId"];
                }
            }
            sql = [NSString stringWithFormat:@"SELECT * FROM 'equipment' WHERE locationId = ?;"];
            set = [db executeQuery:sql, @(locationId)];
        }
        NSInteger index = 0;
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            if (equipment) {
                if (index == 0) {
                    [equipmentIds appendString:@"("];
//                    [equipmentFloorIds appendString:@"("];
//                    [equipmentApartmentIds appendString:@"("];
                    [equipmentTypeIds appendString:@"("];
                }
                else {
                    [equipmentIds appendString:@","];
//                    [equipmentFloorIds appendString:@","];
//                    [equipmentApartmentIds appendString:@","];
                    [equipmentTypeIds appendString:@","];
                }
                [equipmentIds appendString:[NSString stringWithFormat:@"'%@'", equipment.equipmentId]];
//                [equipmentFloorIds appendString:[NSString stringWithFormat:@"%ld", (long)equipment.floorId]];
//                [equipmentApartmentIds appendString:[NSString stringWithFormat:@"%ld", (long)equipment.apartmentId]];
                [equipmentTypeIds appendString:[NSString stringWithFormat:@"%ld", (long)equipment.equipmentTypeId]];
                index++;
            }
        }
        if (equipmentIds.length > 0) {
            [equipmentIds appendString:@")"];
//            [equipmentFloorIds appendString:@")"];
//            [equipmentApartmentIds appendString:@")"];
            [equipmentTypeIds appendString:@")"];
        }
        YWLoginUser* currentUser = [YWLoginTool loginUser];
        if (maintenanceTypeId == YWMaintenanceTypeTrouble) {
            //维修任务（维保任务是没有equipmentId）
            if (qrcodeID) {
                if (equipmentIds.length) {
//                    sql = [NSString stringWithFormat:@"SELECT * FROM mission_trouble where troubleStatus = ? and executorId = ? and qrcodeId=? and equipmentId in %@", equipmentIds];
                    sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' where troubleStatus = ? and executorId = ? and troubleId in (SELECT troubleId FROM 'YW_ReportTrouble' where qrcodeId=? and equipmentId in %@)", equipmentIds];
                    set = [db executeQuery:sql, @(YWTroubleMissionStatusAssign),@(currentUser.uniqueId),qrcodeID];
                }else{
                    set = nil;
                }
                
            }else if (locationId){
//                sql = [NSString stringWithFormat:@"SELECT * FROM mission_trouble where troubleStatus = ? and executorId = ? and locationId=?"];
                sql = [NSString stringWithFormat:@"SELECT * FROM 'YW_TroubleMission' where troubleStatus = ? and executorId = ? and troubleId in (SELECT troubleId FROM 'YW_ReportTrouble' where locationId=?)"];
                set = [db executeQuery:sql, @(YWTroubleMissionStatusAssign),@(currentUser.uniqueId),@(locationId)];
            }
            while ([set next]) {
//                YWTroubleMission* troubleMission = [self troubleMissionWithFMResultSet:set FMDatabase:db];
//                [unfinishedMissions addObject:troubleMission];
                YWTroubleMissionModel * troubleMissionModel = [[YWTroubleMissionDBManager shareManager] troubleMissionModelWithFMResultSet:set FMDatabase:db needSelectReportTrouble:YES];
                [unfinishedMissions addObject:troubleMissionModel];
            }
        }
        else {
            if (equipmentTypeIds.length) {
                sql = [NSString stringWithFormat:@"select * from mission_maintenance where equipmentTypeId in %@ AND missionStatus = %lu AND maintenanceTypeId =%ld AND buildingId ='%@' AND status=0", equipmentTypeIds,(unsigned long)YWMissionStatusUnfinished, (long)maintenanceTypeId,buildingId];
                set = [db executeQuery:sql ];
            }else{
                set = nil;
            }
            while ([set next]) {
                YWMaintenanceMission* maintenanceMission = [YWDetectAndUpkeepDBManager maintenanceMissionWithFMResultSet:set FMDatabase:db];
                if ([maintenanceMission.executorIds rangeOfString:[@(currentUser.uniqueId) stringValue]].location != NSNotFound) {
                    if (maintenanceMission.equipments.count>0) {
                        [unfinishedMissions addObject:maintenanceMission];
                    }else{
                        [unfinishedMissions addObject:maintenanceMission];
                    }
                }
            }
        }
        [db closeOpenResultSets];
    }];
    return unfinishedMissions;
}

- (NSArray*)missionsWithEquipmentId:(NSString*)equipmentId andMaintenanceTypeId:(NSInteger)maintenanceTypeId{
    __block NSMutableArray* unfinisheMissions = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'mission_maintenance' WHERE maintenanceTypeId =? AND missionId in (SELECT missionId FROM 'mission_maintenance_equipment' where equipmentId=?)";
        FMResultSet* set = [db executeQuery:sql,@(maintenanceTypeId), equipmentId];
        if ([set next]) {
            YWMaintenanceMission* maintenanceMission = [YWDetectAndUpkeepDBManager maintenanceMissionWithFMResultSet:set FMDatabase:db];
            [unfinisheMissions addObject:maintenanceMission];
        }
        [db closeOpenResultSets];
    }];
    return unfinisheMissions.count ? unfinisheMissions : nil;
}


- (NSArray *)uploadFailDetectAndUpkeepMission{
    __block NSMutableArray* uploadFailDetectAndUpkeepMissionArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = [NSString stringWithFormat:@"SELECT * FROM 'mission_maintenance' WHERE uploadFail = 1;"];//ORDER BY cutoffTime desc, maintenanceTypeId ASC
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWMaintenanceMission* maintenanceMission = [YWDetectAndUpkeepDBManager maintenanceMissionWithFMResultSet:set FMDatabase:db];
            [uploadFailDetectAndUpkeepMissionArray addObject:maintenanceMission];
        }
        [db closeOpenResultSets];
    }];
    return uploadFailDetectAndUpkeepMissionArray;
}

- (NSArray*)uploadFailedRecordsWithMaintenanceType:(NSInteger)maintenanceType{
    __block NSMutableArray* uploadFailedRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        NSString* tableName = nil;
        if (maintenanceType == YWMaintenanceTypeTrouble) {
            sql = @"SELECT * FROM 'equipment_trouble_record' WHERE (uploadStatus=? or uploadStatus=?) ORDER BY troubleId;";
            FMResultSet* set = [db executeQuery:sql, @(YWEquipmentMaintenanceRecordUploadStatusUnFinished),@(YWEquipmentMaintenanceRecordUploadStatusUploading)];
            while ([set next]) {
                YWEquipmentTroubleRecord* troubleRecord = [self equipmentTroubleRecord:set FMDatabase:db];
                [uploadFailedRecords addObject:troubleRecord];
            }
        }else{
            if (maintenanceType == YWMaintenanceTypeDetection) {
                tableName = @"equipment_detection_record";
            }else if (maintenanceType == YWMaintenanceTypeUpkeep) {
                tableName = @"equipment_upkeep_record";
            }
            if (tableName) {
                sql = [NSString stringWithFormat:@"SELECT * FROM '%@' WHERE (uploadStatus=? or uploadStatus=?) ORDER BY missionId;", tableName];
                FMResultSet* set = [db executeQuery:sql, @(YWEquipmentMaintenanceRecordUploadStatusUnFinished),@(YWEquipmentMaintenanceRecordUploadStatusUploading)];
                while ([set next]) {
                    YWEquipmentMaintenanceRecord* record = [self equipmentMaintenanceRecord:set FMDatabase:db];
                    record.maintenanceTypeId = maintenanceType;
                    [uploadFailedRecords addObject:record];
                }
            }
        }
        
        [db closeOpenResultSets];
    }];
    return uploadFailedRecords;
}


- (BOOL)setUploadFailWithMission:(id)mission
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        if ([mission isKindOfClass:[YWMaintenanceMission class]]) {
            sql = @"UPDATE 'mission_maintenance' SET uploadFail=? WHERE missionId=?;";
            YWMaintenanceMission *maintenanceMission = (YWMaintenanceMission*)mission;
            executeResult = [db executeUpdate:sql, @(maintenanceMission.uploadFail), @(maintenanceMission.missionId)];;
        }else{
            sql = @"UPDATE 'YW_TroubleMission' SET uploadFail=? WHERE troubleId=?;";
//            YWTroubleMission *troubleMission = (YWTroubleMission*)mission;
            YWTroubleMissionModel * troubleMissionModel = (YWTroubleMissionModel*)mission;
            executeResult = [db executeUpdate:sql, @(troubleMissionModel.uploadFail), @(troubleMissionModel.trouble.troubleId)];
        }
        [db closeOpenResultSets];
    }];
    return executeResult;
}


- (BOOL)mofifyMissionStatusWithMissionId:(NSInteger)missionId maintenanceType:(YWMaintenanceType)typeId{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        if (typeId == YWMaintenanceTypeTrouble) {
//            mission_trouble
            sql = @"UPDATE 'YW_TroubleMission' SET troubleStatus=? WHERE troubleId=?;";
            executeResult = [db executeUpdate:sql, @(YWTroubleMissionStatusCancelPostTrouble), @(missionId)];
        }else{
            sql = @"UPDATE 'mission_maintenance' SET status=? WHERE missionId=?;";
            executeResult = [db executeUpdate:sql, @(-1), @(missionId)];
        }
        
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWEquipmentMaintenanceRecord*)equipmentMaintenanceRecord:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWEquipmentMaintenanceRecord* record = [[YWEquipmentMaintenanceRecord alloc] init];
    record.uniqueTag = [set stringForColumn:@"uniqueTag"];
    record.recordId = [set longLongIntForColumn:@"recordId"];
    record.equipmentId = [set stringForColumn:@"equipmentId"];
    record.missionId = [[NSString stringWithFormat:@"%@",[set objectForColumnName:@"missionId"]] integerValue];
    record.note = [set stringForColumn:@"note"];
    record.completeTime = [set longLongIntForColumn:@"completeTime"];
    record.clientScanTime = [set longLongIntForColumn:@"clientScanTime"];
    record.handlerName = [set stringForColumn:@"handlerName"];
    record.uploadStatus = [set intForColumn:@"uploadStatus"];
    record.status = [set intForColumn:@"status"];
    record.maintenanceTypeId = [set intForColumn:@"maintenanceTypeId"];
    record.dayMonthString = [set stringForColumn:@"dayMonthString"];
    record.recordSequence = [set stringForColumn:@"recordSequence"];
    record.missionCycle = [set intForColumn:@"missionCycle"];
    
    NSInteger handlerUniqueId = [set intForColumn:@"handlerUniqueId"];
    NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    FMResultSet *handlerSet = [db executeQuery:sql, @(handlerUniqueId)];
    if ([handlerSet next]) {
        record.handler = [self handlerWithSet:handlerSet];
    }
    
    sql = @"SELECT * FROM 'equipmentFields_record' WHERE uniqueTag = ? AND maintenanceTypeId = ?;";
    FMResultSet* fieldSet = [db executeQuery:sql, record.uniqueTag, @(record.maintenanceTypeId)];
    NSMutableArray *fieldRecordArray = nil;
    while ([fieldSet next]) {
        if (fieldRecordArray == nil) {
            fieldRecordArray = [NSMutableArray array];
        }
        YWEquipmentFieldRecord* fieldRecord = [self equipmentFieldRecord:fieldSet FMDatabase:db];
        [fieldRecordArray addObject:fieldRecord];
    }
    record.equipmentFieldRecord = fieldRecordArray;
    
    return record;
}

- (NSDictionary*)detectAndUpkeepRecordsWithMission:(YWMaintenanceMission*)mission;
{
    YWMaintenanceMission *maintenanceMission = mission;
    __block NSMutableDictionary* missionRecordsDic = [NSMutableDictionary dictionary];
    __block NSMutableArray* allRecords = [NSMutableArray array];
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        NSString* tableName;
        FMResultSet* set = nil;
        if (maintenanceMission.maintenanceTypeId == YWMaintenanceTypeDetection) {
            tableName = @"equipment_detection_record";
        }
        else {
            tableName = @"equipment_upkeep_record";
        }
        if (maintenanceMission.equipments.count==0) {
            sql = [NSString stringWithFormat:@"select a.*,b.locationId from %@ as a inner join equipment as b on a.missionId = ? and a.equipmentId = b.equipmentId ORDER BY a.completeTime asc;", tableName];
            //没有设备也可以看到记录
            //sql = [NSString stringWithFormat:@"select a.*,b.locationId from %@ as a left join equipment as b on a.equipmentId = b.equipmentId where a.missionId = ? ORDER BY a.completeTime asc;", tableName];
            set = [db executeQuery:sql, @(maintenanceMission.missionId)];
            while ([set next]) {
                NSInteger locationId = [set intForColumn:@"locationId"];
                YWEquipmentMaintenanceRecord* equipmentMaintenanceRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
                [allRecords addObject:equipmentMaintenanceRecord];
                NSNumber* locationIdNumber = [NSNumber numberWithInteger:locationId];
                if ([missionRecordsDic.allKeys containsObject:locationIdNumber]) {
                    NSMutableArray* records = [missionRecordsDic objectForKey:locationIdNumber];
                    if (records) {
                        [records addObject:equipmentMaintenanceRecord];
                    }
                }
                else {
                    NSMutableArray* records = [NSMutableArray array];
                    [records addObject:equipmentMaintenanceRecord];
                    [missionRecordsDic setObject:records forKey:locationIdNumber];
                }
            }
        }else{
            sql = [NSString stringWithFormat:@"select a.* from equipment as a left join mission_maintenance_equipment as b on a.equipmentId = b.equipmentId where b.missionId=? ORDER BY locationId;"];
            set = [db executeQuery:sql, @(maintenanceMission.missionId)];
            while ([set next]) {
                YWEquipment *equipment = [self equipmentWithFMResultSet:set];
                NSInteger locationId = equipment.locationId;
                YWEquipmentMaintenanceRecord* equipmentMaintenanceRecord = nil;
                NSString *sql = [NSString stringWithFormat:@"select *from %@ where equipmentId='%@' AND missionId ='%@'",tableName,equipment.equipmentId,@(maintenanceMission.missionId)];
                FMResultSet* recordSet = [db executeQuery:sql];
                if ([recordSet next]) {
                    equipmentMaintenanceRecord = [self equipmentMaintenanceRecord:recordSet FMDatabase:db];
                    [allRecords addObject:equipmentMaintenanceRecord];
                }
                
                NSNumber* locationIdNumber = [NSNumber numberWithInteger:locationId];
                if ([missionRecordsDic.allKeys containsObject:locationIdNumber]) {
                    NSMutableArray* records = [missionRecordsDic objectForKey:locationIdNumber];
                    if (records) {
                        NSDictionary* dataDir = @{ @"equipmentName" : equipment.equipmentName?:@"",@"equipmentId" : equipment.equipmentId?:@"",@"equipmentOwnCode" : equipment.ownCode?:@"",
                                                   @"record" : equipmentMaintenanceRecord?:@""};
                        [records addObject:dataDir];
                    }
                }
                else {
                    NSMutableArray* records = [NSMutableArray array];
                    NSDictionary* dataDir = @{ @"equipmentName" : equipment.equipmentName?:@"",@"equipmentId" : equipment.equipmentId?:@"",@"equipmentOwnCode" : equipment.ownCode?:@"",
                                               @"record" : equipmentMaintenanceRecord?:@""};
                    [records addObject:dataDir];
                    [missionRecordsDic setObject:records forKey:locationIdNumber];
                }
            }
        }
        

        [db closeOpenResultSets];
    }];
    [allRecords enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull maintanceRecord, NSUInteger idx, BOOL* _Nonnull stop) {
        if (maintanceRecord.maintenanceTypeId == YWMaintenanceTypeTrouble) {
            maintanceRecord.recordPictures = [self troublePicturesWithRecordId:maintanceRecord.recordId pictureTroubleType:YWPictureTroubleTypeRecord];
        }
        else {
            maintanceRecord.recordPictures = [self picturesWithRecordId:maintanceRecord.recordId maintenanceType:maintanceRecord.maintenanceTypeId];
        }
    }];
    return missionRecordsDic;
}

#pragma mark - maintenanceRecordsView
/**
 *  名称	设备记录视图 maintenanceRecordsView
 */
- (BOOL)createMaintenanceRecordsView
{
    NSString* dropSql = @"DROP VIEW IF EXISTS maintenanceRecordsView";
    BOOL success = [_fmdb executeUpdate:dropSql];
    if (success) {
        NSString* sql = @"CREATE VIEW IF NOT EXISTS 'maintenanceRecordsView' AS Select completeTime,maintenanceTypeId,recordId,equipmentId FROM (SELECT finishTime AS completeTime,1 AS maintenanceTypeId,uniqueTag AS recordId,equipmentId FROM 'inspectionEquipment_record' WHERE recordType=0 union SELECT completeTime,maintenanceTypeId,recordId,equipmentId FROM 'equipment_detection_record' union SELECT completeTime,maintenanceTypeId,recordId,equipmentId FROM 'equipment_upkeep_record' union SELECT completeTime,maintenanceTypeId,recordId,equipmentId FROM 'equipment_trouble_record' WHERE report = 0) ";
        return [_fmdb executeUpdate:sql];
    }
    return YES;
}

- (NSArray*)maintenanceRecordsWithEquipmentId:(NSString*)equipmentId andPage:(NSInteger)page
{
    __block NSMutableArray* recordsViewArray = [NSMutableArray array];
    __block NSInteger showChount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'maintenanceRecordsView' WHERE equipmentId=? ORDER BY completeTime DESC LIMIT ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId, @(showChount)];

        while ([set next]) {
            YWMaintanceRecordViewModel* recordViewModel = [[YWMaintanceRecordViewModel alloc] init];
            recordViewModel.completeTime = [set longLongIntForColumn:@"completeTime"];
            recordViewModel.maintenanceTypeId = [set intForColumn:@"maintenanceTypeId"];
            recordViewModel.recordId = [set stringForColumn:@"recordId"];
            recordViewModel.equipmentId = [set stringForColumn:@"equipmentId"];
            [recordsViewArray addObject:recordViewModel];
        }
        [db closeOpenResultSets];
    }];
    if (recordsViewArray.count > 0) {
        __block NSMutableArray* allRecords = [NSMutableArray array];
        [self.dbQeue inDatabase:^(FMDatabase* db) {
            [recordsViewArray enumerateObjectsUsingBlock:^(YWMaintanceRecordViewModel* _Nonnull recordViewModel, NSUInteger idx, BOOL* _Nonnull stop) {
                NSString* sql = nil;
                NSString* tableName = nil;
                FMResultSet* set = nil;
                if (recordViewModel.maintenanceTypeId == YWMaintenanceTypePatrol) {
                    sql = @"SELECT  * FROM 'inspectionEquipment_record' WHERE uniqueTag=? AND equipmentId = ? ";
                    set = [db executeQuery:sql, recordViewModel.recordId, recordViewModel.equipmentId];
                }
                else {
                    if (recordViewModel.maintenanceTypeId == YWMaintenanceTypeDetection) {
                        tableName = @"equipment_detection_record";
                    }
                    else if (recordViewModel.maintenanceTypeId == YWMaintenanceTypeUpkeep) {
                        tableName = @"equipment_upkeep_record";
                    }
                    else if (recordViewModel.maintenanceTypeId == YWMaintenanceTypeTrouble) {
                        tableName = @"equipment_trouble_record";
                    }
                    sql = [NSString stringWithFormat:@"SELECT * FROM '%@' WHERE recordId=%@;", tableName, recordViewModel.recordId];
                    set = [db executeQuery:sql];
                }

                while ([set next]) {
                    if ([tableName isEqualToString:@"equipment_trouble_record"]) {
                        YWEquipmentTroubleRecord* troubleRecord = [self equipmentTroubleRecord:set FMDatabase:db];
                        [allRecords addObject:troubleRecord];
                    }
                    else {
                        if (recordViewModel.maintenanceTypeId == YWMaintenanceTypePatrol) {
                            YWInspectionEquipmentRecord* record = [[YWInspectionMissionDBManager shareManager] inspectionEquipmentRecordWithFMResultSet:set FMDatabase:db];
                            [allRecords addObject:record];
                        }
                        else {
                            YWEquipmentMaintenanceRecord* record = [self equipmentMaintenanceRecord:set FMDatabase:db];
                            [allRecords addObject:record];
                        }
                    }
                }
            }];

            [db closeOpenResultSets];
        }];
        return allRecords;
    }
    return nil;
}

#pragma mark - equipment_detection_record table
/**
 *  名称	设备检测记录表 equipment_detection_record
 */
NSString* const KSqlCreateEquipmentDetectionRecordTable = @"CREATE TABLE IF NOT EXISTS 'equipment_detection_record' (uniqueTag varchar,recordId integer NOT NULL UNIQUE,missionId integer NOT NULL,equipmentId varchar(24) NOT NULL,note varchar(200),completeTime timestamp NOT NULL,handlerName varchar(30),uploadStatus smallint DEFAULT 0,status smallint,maintenanceTypeId smallint DEFAULT 2,dayMonthString text,isRead boolean DEFAULT 0,clientScanTime timestamp,recordSequence varchar,handlerUniqueId integer,missionCycle smallint);";

- (BOOL)createEquipmentDetectionRecordTable
{
    return [_fmdb executeUpdate:KSqlCreateEquipmentDetectionRecordTable];
}

- (void)dropAndReCreateEquipmentDetectionRecordTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists equipment_detection_record;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateEquipmentDetectionRecordTable];
        }
    }];
}

- (BOOL)saveEquipmentDetectionRecordWithJsonArray:(NSArray*)equipmentDetectionRecordJsons
{
    __block BOOL executeResult = YES;
    __block NSArray* blockEquipmentDetectionRecordJsons = equipmentDetectionRecordJsons;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockEquipmentDetectionRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
            if (recordJson.missionId != 0) {
                sql = @"DELETE FROM 'equipment_detection_record' WHERE missionId = ? AND equipmentId=? AND (uploadStatus = ? OR uploadStatus=0);";
                executeResult = [db executeUpdate:sql, @(recordJson.missionId), recordJson.equipmentId, @(YWEquipmentMaintenanceRecordUploadStatusFinished)];
            }
            //            else{
            //                sql = @"DELETE FROM 'equipment_detection_record' WHERE uniqueTag = ? AND equipmentId=? AND (uploadStatus = ? OR uploadStatus=0);";
            //                executeResult = [db executeUpdate:sql, recordJson.uniqueTag,recordJson.equipmentId, @(YWEquipmentMaintenanceRecordUploadStatusFinished)];
            //            }

            if (!executeResult) {
                *rollback = YES;
                *stop = YES;
            }
            if (recordJson.pictures.count) {
                if (recordJson.missionId != 0) {
                    sql = @"DELETE FROM 'picture' WHERE maintenanceType=? AND  missionId = ?;";
                    executeResult = [db executeUpdate:sql, @(YWMaintenanceTypeDetection), @(recordJson.missionId)];
                }
                else {
                    sql = @"DELETE FROM 'picture' WHERE maintenanceType=? AND  recordId = ?;";
                    executeResult = [db executeUpdate:sql, @(YWMaintenanceTypeDetection), @(recordJson.recordId)];
                }

                if (!executeResult) {
                    *rollback = YES;
                    *stop = YES;
                }
            }

        }];

        if (executeResult) {
            [blockEquipmentDetectionRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
                if (recordJson.missionId != 0) {
                    sql = @"INSERT INTO 'equipment_detection_record' (uniqueTag,recordId,missionId,equipmentId,note,completeTime,handlerName,status,dayMonthString,recordSequence,handlerUniqueId,missionCycle) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?);";
                    executeResult = [db executeUpdate:sql, recordJson.uniqueTag, @(recordJson.recordId), @(recordJson.missionId), recordJson.equipmentId, recordJson.note, @(recordJson.maintenanceTime), recordJson.handler.userName, @(recordJson.statusTypeId), recordJson.dayMonthString,recordJson.recordSequence,@(recordJson.handler.uniqueId),@(recordJson.missionCycle)];
                }
                else {
                    sql = @"SELECT * FROM 'equipment_detection_record' WHERE uniqueTag=?;";
                    FMResultSet* set = [db executeQuery:sql, recordJson.uniqueTag];

                    if (![set next]) {
                        sql = @"INSERT INTO 'equipment_detection_record' (uniqueTag,recordId,missionId,equipmentId,note,completeTime,handlerName,status,dayMonthString,recordSequence,handlerUniqueId,missionCycle) VALUES (?,?, ?,?, ?, ?,?,?,?,?,?,?);";
                        executeResult = [db executeUpdate:sql, recordJson.uniqueTag, @(recordJson.recordId), @(recordJson.missionId), recordJson.equipmentId, recordJson.note, @(recordJson.maintenanceTime), recordJson.handler.userName, @(recordJson.statusTypeId), recordJson.dayMonthString,recordJson.recordSequence,@(recordJson.handler.uniqueId),@(recordJson.missionCycle)];
                    }
                    else {
                        ////不更新missionId字段，因为是本地生产存进去，网络数据过的临时任务记录id是0
                        sql = @"UPDATE 'equipment_detection_record' SET recordId=?,equipmentId=?,note=?,completeTime=?,handlerName=?,status=?,dayMonthString=?,recordSequence=?,handlerUniqueId=?,missionCycle=? WHERE uniqueTag=?;";
                        executeResult = [db executeUpdate:sql, @(recordJson.recordId), recordJson.equipmentId, recordJson.note, @(recordJson.maintenanceTime), recordJson.handler.userName, @(recordJson.statusTypeId), recordJson.dayMonthString, recordJson.recordSequence,@(recordJson.handler.uniqueId),@(recordJson.missionCycle),recordJson.uniqueTag];
                    }
                }

                [recordJson.pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
                    picture.missionId = recordJson.missionId;
                    picture.recordId = recordJson.recordId;
                    picture.maintenanceType = recordJson.maintenanceTypeId;
                    picture.equipmentId = recordJson.equipmentId;
                    sql = @"INSERT INTO 'picture' (pictureId,pictureName,bigPictureUrl,smallPictureUrl,isLocalImage,uploadStatus,missionId,maintenanceType,equipmentId,pictureTroubleType,recordId) VALUES (?,?,?,?,?,?,?,?,?,?,?)";
                    executeResult = [db executeUpdate:sql, picture.pictureId, picture.pictureName, picture.bigPictureUrl, picture.smallPictureUrl, @(picture.isLocalImage), @(picture.uploadStatus), @(picture.missionId), @(picture.maintenanceType), picture.equipmentId, @(picture.pictureTroubleType), @(recordJson.recordId)];

                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    };
                }];
            }];
        }

        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateEquipmentDetectionRecordWithArray:(NSArray*)equipmentDetectionRecords
{
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [equipmentDetectionRecords enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull detectionRecord, NSUInteger idx, BOOL* _Nonnull stop) {

            sql = @"SELECT * FROM 'equipment_detection_record' WHERE recordId=?;";
            FMResultSet* set = [db executeQuery:sql, @(detectionRecord.recordId)];

            if ([set next]) {
                sql = @"UPDATE 'equipment_detection_record' SET uniqueTag=?,missionId=?,equipmentId=?,note=?,completeTime=?,handlerName=?,status=?,dayMonthString=?,clientScanTime=?,recordSequence=?,handlerUniqueId=?,missionCycle=? WHERE recordId=?;";
                executeResult = [db executeUpdate:sql, detectionRecord.uniqueTag, @(detectionRecord.missionId), detectionRecord.equipmentId, detectionRecord.note, @(detectionRecord.completeTime), detectionRecord.handlerName, @(detectionRecord.status), detectionRecord.dayMonthString,@(detectionRecord.clientScanTime), detectionRecord.recordSequence,@(detectionRecord.handler.uniqueId),@(detectionRecord.missionCycle),@(detectionRecord.recordId)];
            }
            else {
                sql = @"INSERT INTO 'equipment_detection_record' (uniqueTag,recordId,missionId,equipmentId,note,completeTime,handlerName,uploadStatus,status,dayMonthString,clientScanTime,recordSequence,handlerUniqueId,missionCycle) VALUES (?,?, ?,?, ?, ?,?,?,?,?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, detectionRecord.uniqueTag, @(detectionRecord.recordId), @(detectionRecord.missionId), detectionRecord.equipmentId, detectionRecord.note, @(detectionRecord.completeTime), detectionRecord.handlerName, @(detectionRecord.uploadStatus), @(detectionRecord.status), detectionRecord.dayMonthString,@(detectionRecord.clientScanTime),detectionRecord.recordSequence,@(detectionRecord.handler.uniqueId),@(detectionRecord.missionCycle)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray*)detectionRecordsWithEquipmentId:(NSString*)equipmentId
{
    __block NSMutableArray* detectionRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_detection_record' WHERE equipmentId=? ORDER BY completeTime DESC;";
        FMResultSet* set = [db executeQuery:sql, equipmentId];

        while ([set next]) {
            YWEquipmentMaintenanceRecord* detectionRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
            [detectionRecords addObject:detectionRecord];
        }
        [db closeOpenResultSets];
    }];
    return detectionRecords;
}

- (NSArray*)detectionRecordArrayWithEquipmentId:(NSString*)equipmentId withPage:(NSInteger)page{
    __block NSMutableArray* detectionRecords = [NSMutableArray array];
    __block NSInteger showChount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_detection_record' WHERE equipmentId=? ORDER BY completeTime DESC LIMIT ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId,@(showChount)];
        
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWEquipmentMaintenanceRecord* detectionRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:detectionRecord.completeTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:detectionRecord];
            if (![detectionRecords containsObject:array] && array.count) {
                [detectionRecords addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return detectionRecords.count ? detectionRecords : nil;
}

- (NSArray*)detectionRecordsWithQrcodeId:(NSString*)qrcodeId equipmentTypeId:(NSInteger)equipmentTypeId
{
    __block NSMutableArray* detectionRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_detection_record' WHERE equipmentId IN (SELECT equipmentId FROM 'equipment' WHERE qrcodeId=? AND equipmentTypeId=?) ORDER BY completeTime DESC;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId, @(equipmentTypeId)];

        while ([set next]) {
            YWEquipmentMaintenanceRecord* record = [self equipmentMaintenanceRecord:set FMDatabase:db];
            [detectionRecords addObject:record];
        }
        [db closeOpenResultSets];
    }];
    return detectionRecords;
}

- (YWEquipmentMaintenanceRecord*)detectionRecordsWithMissionId:(NSInteger)missionId equipmentId:(NSString*)equipmentId
{
    __block YWEquipmentMaintenanceRecord* detectionRecord = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_detection_record' WHERE missionId=? AND equipmentId=?;";
        FMResultSet* set = [db executeQuery:sql, @(missionId), equipmentId];

        if ([set next]) {
            detectionRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return detectionRecord;
}

- (BOOL)updateEquipmentDetectionRecordUploadStatus:(YWEquipmentMaintenanceRecordUploadStatus)uploadStatus recordId:(NSInteger)recordId
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'equipment_detection_record' SET uploadStatus=? WHERE recordId=?;";
        executeResult = [db executeUpdate:sql, @(uploadStatus), @(recordId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

#pragma mark - equipment_upkeep_record table
/**
 *  名称	设备保养记录表 equipment_upkeep_record
 */

NSString *const KSqlCreateEquipmentUpkeepRecordTable = @"CREATE TABLE IF NOT EXISTS 'equipment_upkeep_record' (uniqueTag varchar,recordId integer NOT NULL UNIQUE,missionId integer NOT NULL,equipmentId varchar(24) NOT NULL,note varchar(200),completeTime timestamp NOT NULL,handlerName varchar(30),uploadStatus smallint DEFAULT 0,status smallint,maintenanceTypeId smallint DEFAULT 3,dayMonthString text,isRead boolean DEFAULT 0,clientScanTime timestamp,recordSequence varchar,handlerUniqueId integer,missionCycle smallint);";

- (BOOL)createEquipmentUpkeepRecordTable
{
    return [_fmdb executeUpdate:KSqlCreateEquipmentUpkeepRecordTable];
}

- (void)dropAndReCreateEquipmentUpkeepRecordTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists equipment_upkeep_record;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateEquipmentUpkeepRecordTable];
        }
    }];
}

- (BOOL)saveEquipmentUpkeepRecordWithJsonArray:(NSArray*)equipmentUpkeepRecordJsons
{
    __block BOOL executeResult = YES;
    __block NSArray* blockEquipmentUpkeepRecordJsons = equipmentUpkeepRecordJsons;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockEquipmentUpkeepRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
            if (recordJson.missionId != 0) {
                sql = @"DELETE FROM 'equipment_upkeep_record' WHERE missionId = ? AND equipmentId=? AND (uploadStatus = ? OR uploadStatus=0);";
                executeResult = [db executeUpdate:sql, @(recordJson.missionId), recordJson.equipmentId, @(YWEquipmentMaintenanceRecordUploadStatusFinished)];
            }
            //            else{
            //                sql = @"DELETE FROM 'equipment_upkeep_record' WHERE uniqueTag = ? AND equipmentId=? AND (uploadStatus = ? OR uploadStatus=0);";
            //                executeResult = [db executeUpdate:sql, recordJson.uniqueTag,recordJson.equipmentId, @(YWEquipmentMaintenanceRecordUploadStatusFinished)];
            //            }

            if (!executeResult) {
                *rollback = YES;
                *stop = YES;
            }
            if (recordJson.pictures.count) {
                if (recordJson.missionId != 0) {
                    sql = @"DELETE FROM 'picture' WHERE maintenanceType=? AND  missionId = ?;";
                    executeResult = [db executeUpdate:sql, @(YWMaintenanceTypeUpkeep), @(recordJson.missionId)];
                }
                else {
                    sql = @"DELETE FROM 'picture' WHERE maintenanceType=? AND  recordId = ?;";
                    executeResult = [db executeUpdate:sql, @(YWMaintenanceTypeUpkeep), @(recordJson.recordId)];
                }
                if (!executeResult) {
                    *rollback = YES;
                    *stop = YES;
                }
            }

        }];

        if (executeResult) {
            [blockEquipmentUpkeepRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
                if (recordJson.missionId != 0) {
                    sql = @"INSERT INTO 'equipment_upkeep_record' (uniqueTag,recordId,missionId,equipmentId,note,completeTime,handlerName,status,dayMonthString,recordSequence,handlerUniqueId,missionCycle) VALUES (?,?, ?,?, ?, ?,?,?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, recordJson.uniqueTag, @(recordJson.recordId), @(recordJson.missionId), recordJson.equipmentId, recordJson.note, @(recordJson.maintenanceTime), recordJson.handler.userName, @(recordJson.statusTypeId), recordJson.dayMonthString,recordJson.recordSequence,@(recordJson.handler.uniqueId),@(recordJson.missionCycle)];
                }
                else {
                    sql = @"SELECT * FROM 'equipment_upkeep_record' WHERE uniqueTag=?;";
                    FMResultSet* set = [db executeQuery:sql, recordJson.uniqueTag];

                    if (![set next]) {
                        sql = @"INSERT INTO 'equipment_upkeep_record' (uniqueTag,recordId,missionId,equipmentId,note,completeTime,handlerName,status,dayMonthString,recordSequence,handlerUniqueId,missionCycle) VALUES (?,?, ?,?, ?, ?,?,?,?,?,?,?);";
                        executeResult = [db executeUpdate:sql, recordJson.uniqueTag, @(recordJson.recordId), @(recordJson.missionId), recordJson.equipmentId, recordJson.note, @(recordJson.maintenanceTime), recordJson.handler.userName, @(recordJson.statusTypeId), recordJson.dayMonthString,recordJson.recordSequence,@(recordJson.handler.uniqueId),@(recordJson.missionCycle)];
                    }
                    else {
                        ////不更新missionId字段，因为是本地生产存进去，网络数据过的临时任务记录id是0
                        sql = @"UPDATE 'equipment_upkeep_record' SET recordId=?,equipmentId=?,note=?,completeTime=?,handlerName=?,status=?,dayMonthString=?,recordSequence=?,handlerUniqueId=?,missionCycle=? WHERE uniqueTag=?;";
                        executeResult = [db executeUpdate:sql, @(recordJson.recordId), recordJson.equipmentId, recordJson.note, @(recordJson.maintenanceTime), recordJson.handler.userName, @(recordJson.statusTypeId), recordJson.dayMonthString, recordJson.recordSequence,@(recordJson.handler.uniqueId),@(recordJson.missionCycle),recordJson.uniqueTag];
                    }
                }

                [recordJson.pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
                    picture.missionId = recordJson.missionId;
                    picture.recordId = recordJson.recordId;
                    picture.maintenanceType = recordJson.maintenanceTypeId;
                    picture.equipmentId = recordJson.equipmentId;

                    sql = @"INSERT INTO 'picture' (pictureId,pictureName,bigPictureUrl,smallPictureUrl,isLocalImage,uploadStatus,missionId,maintenanceType,equipmentId,pictureTroubleType,recordId) VALUES (?, ?, ?, ?, ?, ?, ?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, picture.pictureId, picture.pictureName, picture.bigPictureUrl, picture.smallPictureUrl, @(picture.isLocalImage), @(picture.uploadStatus), @(picture.missionId), @(picture.maintenanceType), picture.equipmentId, @(picture.pictureTroubleType), @(recordJson.recordId)];

                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    };
                }];
            }];
        }

        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateEquipmentUpkeepRecordWithArray:(NSArray*)equipmentUpkeepRecords
{
    __block BOOL executeResult = YES;
    __block NSArray* blockEquipmentUpkeepRecords = equipmentUpkeepRecords;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {

        [blockEquipmentUpkeepRecords enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull upkeepRecord, NSUInteger idx, BOOL* _Nonnull stop) {

            sql = @"SELECT * FROM 'equipment_upkeep_record' WHERE recordId=?;";
            FMResultSet* set = [db executeQuery:sql, @(upkeepRecord.recordId)];

            if ([set next]) {
                sql = @"UPDATE 'equipment_upkeep_record' SET uniqueTag=?,missionId=?,equipmentId=?,note=?,completeTime=?,handlerName=?,status=?,dayMonthString=?,clientScanTime=?,recordSequence=?,handlerUniqueId=?,missionCycle=? WHERE recordId=?;";
                executeResult = [db executeUpdate:sql, upkeepRecord.uniqueTag, @(upkeepRecord.missionId), upkeepRecord.equipmentId, upkeepRecord.note, @(upkeepRecord.completeTime), upkeepRecord.handlerName, @(upkeepRecord.status), upkeepRecord.dayMonthString,@(upkeepRecord.clientScanTime), upkeepRecord.recordSequence,@(upkeepRecord.handler.uniqueId),@(upkeepRecord.missionCycle),@(upkeepRecord.recordId)];
            }
            else {
                sql = @"INSERT INTO 'equipment_upkeep_record' (uniqueTag,recordId,missionId,equipmentId,note,completeTime,handlerName,uploadStatus,status,dayMonthString,clientScanTime,recordSequence,handlerUniqueId,missionCycle) VALUES (?,?, ?,?, ?, ?,?,?,?,?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, upkeepRecord.uniqueTag, @(upkeepRecord.recordId), @(upkeepRecord.missionId), upkeepRecord.equipmentId, upkeepRecord.note, @(upkeepRecord.completeTime), upkeepRecord.handlerName, @(upkeepRecord.uploadStatus), @(upkeepRecord.status), upkeepRecord.dayMonthString,@(upkeepRecord.clientScanTime),upkeepRecord.recordSequence,@(upkeepRecord.handler.uniqueId),@(upkeepRecord.missionCycle)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray*)upkeepRecordsWithEquipmentId:(NSString*)equipmentId
{
    __block NSMutableArray* upkeepRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_upkeep_record' WHERE equipmentId=? ORDER BY completeTime DESC;";
        FMResultSet* set = [db executeQuery:sql, equipmentId];

        while ([set next]) {
            YWEquipmentMaintenanceRecord* upkeepRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
            //            upkeepRecord.maintenanceTypeId = YWMaintenanceTypeUpkeep;
            [upkeepRecords addObject:upkeepRecord];
        }
        [db closeOpenResultSets];
    }];
    return upkeepRecords;
}

- (NSArray*)upkeepRecordArrayWithEquipmentId:(NSString*)equipmentId withPage:(NSInteger)page{
    __block NSMutableArray* upkeepRecords = [NSMutableArray array];
    __block NSInteger showChount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_upkeep_record' WHERE equipmentId=? ORDER BY completeTime DESC LIMIT ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId,@(showChount)];
        
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWEquipmentMaintenanceRecord* upkeepRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
            //            upkeepRecord.maintenanceTypeId = YWMaintenanceTypeUpkeep;
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:upkeepRecord.completeTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:upkeepRecord];
            if (![upkeepRecords containsObject:array] && array.count) {
                [upkeepRecords addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return upkeepRecords.count ? upkeepRecords : nil;
}

- (NSArray*)upkeepRecordsWithQrcodeId:(NSString*)qrcodeId equipmentTypeId:(NSInteger)equipmentTypeId
{
    __block NSMutableArray* upkeepRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_upkeep_record' WHERE equipmentId IN (SELECT equipmentId FROM 'equipment' WHERE qrcodeId=? AND equipmentTypeId=?) ORDER BY completeTime DESC;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId, @(equipmentTypeId)];

        while ([set next]) {
            YWEquipmentMaintenanceRecord* record = [self equipmentMaintenanceRecord:set FMDatabase:db];
            [upkeepRecords addObject:record];
        }
        [db closeOpenResultSets];
    }];
    return upkeepRecords;
}

- (YWEquipmentMaintenanceRecord*)upkeepRecordsWithMissionId:(NSInteger)missionId equipmentId:(NSString*)equipmentId;
{
    __block YWEquipmentMaintenanceRecord* upkeepRecord = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_upkeep_record' WHERE missionId=? AND equipmentId=?;";
        FMResultSet* set = [db executeQuery:sql, @(missionId), equipmentId];

        if ([set next]) {
            upkeepRecord = [self equipmentMaintenanceRecord:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return upkeepRecord;
}

- (BOOL)updateEquipmentUpkeepRecordUploadStatus:(YWEquipmentMaintenanceRecordUploadStatus)uploadStatus recordId:(NSInteger)recordId
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'equipment_upkeep_record' SET uploadStatus=? WHERE recordId=?;";
        executeResult = [db executeUpdate:sql, @(uploadStatus), @(recordId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

#pragma mark - equipment_trouble_record table
/**
 *  名称	设备维修记录表 equipment_trouble_record
 */
NSString *const KSqlCreateEquipmentTroubleRecordTable = @"CREATE TABLE IF NOT EXISTS 'equipment_trouble_record' (uniqueTag varchar,recordId integer NOT NULL UNIQUE,troubleId integer NOT NULL,equipmentId varchar(24),note varchar(200),completeTime timestamp NOT NULL,reasonId smallint NOT NULL,replacementStatus smallint,replacementName varchar(100),recordType smallint NOT NULL,handlerName varchar(30),uploadStatus smallint DEFAULT 0,report boolean DEFAULT 0,equipmentTypeId integer,reporterName varchar(100),reporterNumber varchar(100),reportNote varchar(200),reportTime timestamp,qrcodeId varchar(19),maintenanceTypeId smallint DEFAULT 4,dayMonthString text,clientScanTime timestamp,laborCosts varchar,materialCosts varchar,recordSequence varchar,handlerUniqueId integer);";

- (BOOL)createEquipmentTroubleRecordTable
{
    return [_fmdb executeUpdate:KSqlCreateEquipmentTroubleRecordTable];
}

- (void)dropAndReCreateEquipmentTroubleRecordTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists equipment_trouble_record;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateEquipmentTroubleRecordTable];
        }
    }];
}

- (BOOL)saveEquipmentTroubleRecordWithJsonArray:(NSArray*)equipmentTroubleRecordJsons{
    if (equipmentTroubleRecordJsons.count==0) {
        return YES;
    }
    //保存运行参数记录
    NSMutableArray* fieldRecorsArray = [NSMutableArray array];
    [equipmentTroubleRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentTroubleRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
        [recordJson.equipmentFields enumerateObjectsUsingBlock:^(YWEquipmentFieldRecord* _Nonnull fieldRecord, NSUInteger idx, BOOL* _Nonnull stop) {
            fieldRecord.uniqueTag = recordJson.uniqueTag;
            fieldRecord.maintenanceTypeId = YWMaintenanceTypeTrouble;
            [fieldRecorsArray addObject:fieldRecord];
        }];
        [recordJson.pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
            picture.missionId = recordJson.missionId;
            picture.recordId = recordJson.recordId;
            picture.maintenanceType = recordJson.maintenanceTypeId;
            picture.equipmentId = recordJson.equipmentId;
        }];
    }];
    [self updateEquipmentFieldRecords:fieldRecorsArray];
    //保存维修记录
    __block BOOL executeResult = YES;
    __block NSArray* blockEquipmentTroubleRecordJsons = equipmentTroubleRecordJsons;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockEquipmentTroubleRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentTroubleRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
            if (recordJson.troubleId != 0) {
                sql = @"DELETE FROM 'equipment_trouble_record' WHERE troubleId = ?;";
                executeResult = [db executeUpdate:sql, @(recordJson.troubleId)];
            }
            //            else{
            //                sql = @"DELETE FROM 'equipment_trouble_record' WHERE uniqueTag = ?;";
            //                executeResult = [db executeUpdate:sql, recordJson.uniqueTag];
            //            }

            if (!executeResult) {
                *rollback = YES;
                *stop = YES;
            }
            if (recordJson.pictures.count) {
                if (recordJson.troubleId != 0) {
                    ////YWPictureTroubleTypeRecord = 1 //维修记录产生的图片  维修
                    sql = @"DELETE FROM 'picture' WHERE missionId = ? AND maintenanceType=? AND pictureTroubleType=?;";
                    executeResult = [db executeUpdate:sql, @(recordJson.troubleId), @(YWMaintenanceTypeTrouble), @(YWPictureTroubleTypeRecord)];
                }
                else {
                    sql = @"DELETE FROM 'picture' WHERE recordId = ? AND maintenanceType=? AND pictureTroubleType=?;";
                    executeResult = [db executeUpdate:sql, @(recordJson.recordId), @(YWMaintenanceTypeTrouble), @(YWPictureTroubleTypeRecord)];
                }

                if (!executeResult) {
                    *rollback = YES;
                    *stop = YES;
                }
            }
            
        }];

        if (executeResult) {
            [blockEquipmentTroubleRecordJsons enumerateObjectsUsingBlock:^(YWEquipmentTroubleRecordJson* _Nonnull recordJson, NSUInteger idx, BOOL* _Nonnull stop) {
                if (!recordJson.reporter.mobile) {
                    sql = @"SELECT mobile FROM 'handler' WHERE uniqueId = ?;";
                    FMResultSet *handlerSet = [db executeQuery:sql, @(recordJson.reporter.uniqueId)];
                    if ([handlerSet next]) {
                        NSString *mobile = [handlerSet stringForColumn:@"mobile"];
                        recordJson.reporter.mobile = mobile.length?mobile:nil;
                    }
                }
                
                if (recordJson.troubleId != 0) {
                    sql = @"INSERT INTO 'equipment_trouble_record' (uniqueTag,recordId,troubleId,equipmentId,note,completeTime,reasonId,replacementStatus,replacementName,recordType,handlerName,equipmentTypeId,reporterName,reporterNumber,reportNote,reportTime,qrcodeId,dayMonthString,laborCosts,materialCosts,recordSequence,handlerUniqueId) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, recordJson.uniqueTag, @(recordJson.recordId), @(recordJson.troubleId), recordJson.equipmentId, recordJson.note, @(recordJson.createTime), @(recordJson.reasonId), @(recordJson.replacementStatus), recordJson.replacementName, @(recordJson.recordType), recordJson.handler.userName, @(recordJson.equipmentType.equipmentTypeId), recordJson.reporter.userName, recordJson.reporter.mobile, recordJson.reportNote, @(recordJson.reportTime), recordJson.qrcodeId, recordJson.dayMonthString,recordJson.laborCosts,recordJson.materialCosts,recordJson.recordSequence,@(recordJson.handler.uniqueId)];
                }
                else {
                    sql = @"SELECT * FROM 'equipment_trouble_record' WHERE uniqueTag=?;";
                    FMResultSet* set = [db executeQuery:sql, recordJson.uniqueTag];

                    if (![set next]) {
                        sql = @"INSERT INTO 'equipment_trouble_record' (uniqueTag,recordId,troubleId,equipmentId,note,completeTime,reasonId,replacementStatus,replacementName,recordType,handlerName,equipmentTypeId,reporterName,reporterNumber,reportNote,reportTime,qrcodeId,dayMonthString,laborCosts,materialCosts,recordSequence,handlerUniqueId) VALUES (?, ?,?, ?, ?,?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
                        executeResult = [db executeUpdate:sql, recordJson.uniqueTag, @(recordJson.recordId), @(recordJson.troubleId), recordJson.equipmentId, recordJson.note, @(recordJson.createTime), @(recordJson.reasonId), @(recordJson.replacementStatus), recordJson.replacementName, @(recordJson.recordType), recordJson.handler.userName, @(recordJson.equipmentType.equipmentTypeId), recordJson.reporter.userName, recordJson.reporter.mobile, recordJson.reportNote, @(recordJson.reportTime), recordJson.qrcodeId, recordJson.dayMonthString,recordJson.laborCosts,recordJson.materialCosts,recordJson.recordSequence,@(recordJson.handler.uniqueId)];
                    }
                    else {
                        ////不更新troubleId字段，因为是本地生产存进去，网络数据过的临时任务记录id是0
                        sql = @"UPDATE 'equipment_trouble_record' SET recordId=?,equipmentId=?,note=?,completeTime=?,reasonId=?,replacementStatus=?,replacementName=?,recordType=?,handlerName=?,equipmentTypeId=?,reporterName=?,reporterNumber=?,reportNote=?,reportTime=?,qrcodeId=?,dayMonthString=?,laborCosts=?,materialCosts=?,recordSequence=?,handlerUniqueId=? WHERE uniqueTag=?;";
                        executeResult = [db executeUpdate:sql, @(recordJson.recordId), recordJson.equipmentId, recordJson.note, @(recordJson.createTime), @(recordJson.reasonId), @(recordJson.replacementStatus), recordJson.replacementName, @(recordJson.recordType), recordJson.handler.userName, @(recordJson.equipmentType.equipmentTypeId), recordJson.reporter.userName, recordJson.reporter.mobile, recordJson.reportNote, @(recordJson.reportTime), recordJson.qrcodeId, recordJson.dayMonthString,recordJson.laborCosts,recordJson.materialCosts, recordJson.recordSequence,@(recordJson.handler.uniqueId),recordJson.uniqueTag];
                    }
                }

                [recordJson.pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
                    picture.missionId = recordJson.troubleId;
                    picture.recordId = recordJson.recordId;
                    picture.maintenanceType = YWMaintenanceTypeTrouble;
                    picture.equipmentId = recordJson.equipmentId;
                    
                    sql = @"INSERT INTO 'picture' (pictureId,pictureName,bigPictureUrl,smallPictureUrl,isLocalImage,uploadStatus,missionId,maintenanceType,equipmentId,pictureTroubleType,recordId) VALUES (?,?,?,?,?,?,?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, picture.pictureId, picture.pictureName, picture.bigPictureUrl, picture.smallPictureUrl, @(picture.isLocalImage), @(picture.uploadStatus), @(picture.missionId), @(picture.maintenanceType), picture.equipmentId, @(YWPictureTroubleTypeRecord), @(recordJson.recordId)];

                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    }
                }];
                sql = @"DELETE FROM 'picture' WHERE missionId = ? AND maintenanceType=? AND pictureTroubleType=?;";
                executeResult = [db executeUpdate:sql, @(recordJson.troubleId), @(YWMaintenanceTypeTrouble), @(YWPictureTroubleTypeMission)];
                if (!executeResult) {
                    *rollback = YES;
                    *stop = YES;
                }

                [recordJson.trouble.pictures enumerateObjectsUsingBlock:^(YWPicture* _Nonnull picture, NSUInteger idx, BOOL* _Nonnull stop) {
                    picture.missionId = recordJson.troubleId;
                    picture.recordId = recordJson.recordId;
                    picture.maintenanceType = YWMaintenanceTypeTrouble;
                    picture.equipmentId = recordJson.equipmentId;

                    sql = @"INSERT INTO 'picture' (pictureId,pictureName,bigPictureUrl,smallPictureUrl,isLocalImage,uploadStatus,missionId,maintenanceType,equipmentId,pictureTroubleType) VALUES (?,?,?,?,?,?,?,?,?,?);";
                    executeResult = [db executeUpdate:sql, picture.pictureId, picture.pictureName, picture.bigPictureUrl, picture.smallPictureUrl, @(picture.isLocalImage), @(picture.uploadStatus), @(picture.missionId), @(picture.maintenanceType), picture.equipmentId, @(YWPictureTroubleTypeMission)];

                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    }
                }];
            }];
        }

        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateEquipmentTroubleRecordWithArray:(NSArray*)equipmentTroubleRecords
{
    __block BOOL executeResult = YES;
    __block NSArray* blockEquipmentTroubleRecords = equipmentTroubleRecords;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {

        [blockEquipmentTroubleRecords enumerateObjectsUsingBlock:^(YWEquipmentTroubleRecord* _Nonnull malfunctionRecord, NSUInteger idx, BOOL* _Nonnull stop) {
            
            sql = @"SELECT * FROM 'equipment_trouble_record' WHERE recordId=?;";
            FMResultSet* set = [db executeQuery:sql, @(malfunctionRecord.recordId)];

            if ([set next]) {
                sql = @"UPDATE 'equipment_trouble_record' SET uniqueTag=?,troubleId=?,equipmentId=?,note=?,completeTime=?,reasonId=?,replacementStatus=?,replacementName=?,recordType=?,handlerName=?,equipmentTypeId=?,reporterName = ?,reporterNumber = ?,reportNote = ?,reportTime=?,qrcodeId=?,dayMonthString=?,clientScanTime=?,laborCosts=?,materialCosts=?,recordSequence=?,handlerUniqueId=? WHERE recordId=?;";
                executeResult = [db executeUpdate:sql, malfunctionRecord.uniqueTag, @(malfunctionRecord.missionId), malfunctionRecord.equipmentId, malfunctionRecord.note, @(malfunctionRecord.completeTime), @(malfunctionRecord.reasonId), @(malfunctionRecord.replacementStatus), malfunctionRecord.replacementName, @(malfunctionRecord.recordType), malfunctionRecord.handlerName, @(malfunctionRecord.equipmentTypeId), malfunctionRecord.reporterName, malfunctionRecord.reporterNumber, malfunctionRecord.reportNote, @(malfunctionRecord.reportTime), malfunctionRecord.qrcodeId, malfunctionRecord.dayMonthString,@(malfunctionRecord.clientScanTime),malfunctionRecord.laborCosts,malfunctionRecord.materialCosts, malfunctionRecord.recordSequence,@(malfunctionRecord.handler.uniqueId),@(malfunctionRecord.recordId)];
            }else {
                sql = @"INSERT INTO 'equipment_trouble_record' (uniqueTag,recordId,troubleId,equipmentId,note,completeTime,reasonId,replacementStatus,replacementName,recordType,handlerName,uploadStatus,report,equipmentTypeId,reporterName,reporterNumber,reportNote,reportTime,qrcodeId,dayMonthString,clientScanTime,laborCosts,materialCosts,recordSequence,handlerUniqueId) VALUES (?,?, ?, ?,?, ?, ?,?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, malfunctionRecord.uniqueTag, @(malfunctionRecord.recordId), @(malfunctionRecord.missionId), malfunctionRecord.equipmentId, malfunctionRecord.note, @(malfunctionRecord.completeTime), @(malfunctionRecord.reasonId), @(malfunctionRecord.replacementStatus), malfunctionRecord.replacementName, @(malfunctionRecord.recordType), malfunctionRecord.handlerName, @(malfunctionRecord.uploadStatus), @(malfunctionRecord.report), @(malfunctionRecord.equipmentTypeId), malfunctionRecord.reporterName, malfunctionRecord.reporterNumber, malfunctionRecord.reportNote, @(malfunctionRecord.reportTime), malfunctionRecord.qrcodeId, malfunctionRecord.dayMonthString,@(malfunctionRecord.clientScanTime),malfunctionRecord.laborCosts,malfunctionRecord.materialCosts,malfunctionRecord.recordSequence,@(malfunctionRecord.handler.uniqueId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWEquipmentTroubleRecord*)equipmentTroubleRecord:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWEquipmentTroubleRecord* troubleRecord = [[YWEquipmentTroubleRecord alloc] init];
    troubleRecord.uniqueTag = [set stringForColumn:@"uniqueTag"];
    troubleRecord.recordId = [set intForColumn:@"recordId"];
    troubleRecord.equipmentId = [set stringForColumn:@"equipmentId"];
    troubleRecord.missionId = [[NSString stringWithFormat:@"%@",[set objectForColumnName:@"troubleId"]] integerValue];
    troubleRecord.troubleId = troubleRecord.missionId;
    troubleRecord.note = [set stringForColumn:@"note"];
    troubleRecord.completeTime = [set longLongIntForColumn:@"completeTime"];
    troubleRecord.reasonId = [set intForColumn:@"reasonId"];
    troubleRecord.replacementStatus = [set intForColumn:@"replacementStatus"];
    troubleRecord.replacementName = [set stringForColumn:@"replacementName"];
    troubleRecord.recordType = [set intForColumn:@"recordType"];
    troubleRecord.handlerName = [set stringForColumn:@"handlerName"];
    troubleRecord.uploadStatus = [set intForColumn:@"uploadStatus"];
    troubleRecord.report = [set boolForColumn:@"report"];
    troubleRecord.equipmentTypeId = [set intForColumn:@"equipmentTypeId"];
    troubleRecord.reporterName = [set stringForColumn:@"reporterName"];
    troubleRecord.reporterNumber = [set stringForColumn:@"reporterNumber"];
    troubleRecord.reportNote = [set stringForColumn:@"reportNote"];
    troubleRecord.reportTime = [set longLongIntForColumn:@"reportTime"];
    troubleRecord.qrcodeId = [set stringForColumn:@"qrcodeId"];
    troubleRecord.maintenanceTypeId = YWMaintenanceTypeTrouble;
    troubleRecord.dayMonthString = [set stringForColumn:@"dayMonthString"];
    troubleRecord.clientScanTime = [set longLongIntForColumn:@"clientScanTime"];
    troubleRecord.laborCosts = [set stringForColumn:@"laborCosts"];
    troubleRecord.materialCosts = [set stringForColumn:@"materialCosts"];
    troubleRecord.recordSequence = [set stringForColumn:@"recordSequence"];
    
    NSInteger handlerUniqueId = [set intForColumn:@"handlerUniqueId"];
    NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
    FMResultSet *handlerSet = [db executeQuery:sql, @(handlerUniqueId)];
    if ([handlerSet next]) {
        troubleRecord.handler = [self handlerWithSet:handlerSet];
    }
    
    sql = @"SELECT * FROM 'equipmentFields_record' WHERE uniqueTag = ? AND maintenanceTypeId = ?;";
    FMResultSet* fieldSet = [db executeQuery:sql, troubleRecord.uniqueTag, @(troubleRecord.maintenanceTypeId)];
    NSMutableArray *fieldRecordArray = nil;
    while ([fieldSet next]) {
        if (fieldRecordArray == nil) {
            fieldRecordArray = [NSMutableArray array];
        }
        YWEquipmentFieldRecord* fieldRecord = [self equipmentFieldRecord:fieldSet FMDatabase:db];
        [fieldRecordArray addObject:fieldRecord];
    }
    troubleRecord.equipmentFieldRecord = fieldRecordArray;
    
    return troubleRecord;
}

- (YWEquipmentFieldRecord*)equipmentFieldRecord:(FMResultSet*)set FMDatabase:(FMDatabase*)db{
    YWEquipmentFieldRecord* fieldRecord = [[YWEquipmentFieldRecord alloc] init];
    fieldRecord.uniqueTag = [set stringForColumn:@"uniqueTag"];
    fieldRecord.fieldId = [set intForColumn:@"fieldId"];
    fieldRecord.fieldName = [set stringForColumn:@"fieldName"];
    fieldRecord.fieldValue = [set stringForColumn:@"fieldValue"];
    fieldRecord.maintenanceTypeId = [set intForColumn:@"maintenanceTypeId"];
    fieldRecord.fieldTypeId = [set intForColumn:@"fieldTypeId"];
    YWEquipmentFieldOption *option = [[YWEquipmentFieldOption alloc] init];
    option.fieldOptionId = [set intForColumn:@"optionId"];
    option.fieldOptionText = [set stringForColumn:@"optionText"];
    fieldRecord.fieldOption = option;
    return fieldRecord;
}

- (NSArray*)troubleRecordArrayWithEquipmentId:(NSString*)equipmentId andPage:(NSInteger)page{
    __block NSMutableArray* troubleRecords = [NSMutableArray array];
    NSInteger showCount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_trouble_record' WHERE equipmentId=? AND report = 0 ORDER BY completeTime DESC LIMIT ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId,@(showCount)];
        
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWEquipmentTroubleRecord* troubleRecord = [self equipmentTroubleRecord:set FMDatabase:db];
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:troubleRecord.completeTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:troubleRecord];
            if (![troubleRecords containsObject:array] && array.count) {
                [troubleRecords addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return troubleRecords.count ? troubleRecords : nil;
}

- (YWEquipmentTroubleRecord*)troubleRecordWithMissionId:(NSInteger)missionId
{
    __block YWEquipmentTroubleRecord* troubleRecord = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_trouble_record' WHERE troubleId=? AND report = 0;";
        FMResultSet* set = [db executeQuery:sql, @(missionId)];

        if ([set next]) {
            troubleRecord = [self equipmentTroubleRecord:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return troubleRecord;
}

- (BOOL)updateEquipmentTroubleRecordUploadStatus:(YWEquipmentMaintenanceRecordUploadStatus)uploadStatus recordId:(NSInteger)recordId
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'equipment_trouble_record' SET uploadStatus=? WHERE recordId=?;";
        executeResult = [db executeUpdate:sql, @(uploadStatus), @(recordId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}


- (NSArray*)finishedUnUploadMaintenanceRecordWithMission:(YWMission*)mission
{
    if (![mission isKindOfClass:[YWMaintenanceMission class]]) {
        return nil;
    }
    YWMaintenanceMission *maintenanceMission = (YWMaintenanceMission*)mission;
    __block NSMutableArray* maintenanceRecords = [NSMutableArray array];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        NSString* tableName = nil;
        if (maintenanceMission.maintenanceTypeId == YWMaintenanceTypeDetection) {
            tableName = @"equipment_detection_record";
        }else {
            tableName = @"equipment_upkeep_record";
        }
        NSString* sql = [NSString stringWithFormat:@"SELECT * FROM '%@' WHERE (uploadStatus=%lu or uploadStatus=%lu) AND missionId =%ld ORDER BY missionId;", tableName,(unsigned long)YWEquipmentMaintenanceRecordUploadStatusUnFinished,(unsigned long)YWEquipmentMaintenanceRecordUploadStatusUploading, (long)maintenanceMission.missionId];
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWEquipmentMaintenanceRecord* record = [self equipmentMaintenanceRecord:set FMDatabase:db];
            record.maintenanceTypeId = maintenanceMission.maintenanceTypeId;
            [maintenanceRecords addObject:record];
        }

        [db closeOpenResultSets];
    }];
    return maintenanceRecords;
}

- (NSArray*)finishedUnUploadTroubleRecord:(NSInteger)missionId
{
    __block NSMutableArray* troubleRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_trouble_record' WHERE (uploadStatus=? or uploadStatus=?) AND troubleId =?;";
        FMResultSet* set = [db executeQuery:sql, @(YWEquipmentMaintenanceRecordUploadStatusUnFinished),@(YWEquipmentMaintenanceRecordUploadStatusUploading), @(missionId)];
        while ([set next]) {
            YWEquipmentTroubleRecord* troubleRecord = [self equipmentTroubleRecord:set FMDatabase:db];
            [troubleRecords addObject:troubleRecord];
        }
        [db closeOpenResultSets];
    }];
    return troubleRecords;
}

- (NSArray*)equipmentsOfMaintentanceMission:(YWMission*)mission
{
    if (![mission isKindOfClass:[YWMaintenanceMission class]]) {
        return nil;
    }
    YWMaintenanceMission *maintenanceMission = (YWMaintenanceMission*)mission;
    __block NSMutableArray* equipments = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* tableName = nil;
//        if (mission.maintenanceTypeId == YWMaintenanceTypePatrol) {
//            tableName = @"equipment_patrol_record";
//        }
//        else
            if (maintenanceMission.maintenanceTypeId == YWMaintenanceTypeDetection) {
            tableName = @"equipment_detection_record";
        }
        else if (maintenanceMission.maintenanceTypeId == YWMaintenanceTypeUpkeep) {
            tableName = @"equipment_upkeep_record";
        }
        NSString* sql = [NSString stringWithFormat:@"SELECT * FROM 'equipment' WHERE equipmentId in (SELECT equipmentId FROM %@ WHERE missionId = ?)", tableName];
        FMResultSet* set = [db executeQuery:sql, @(maintenanceMission.missionId)];
        while ([set next]) {
            YWEquipment* equipment = [self equipmentWithFMResultSet:set];
            if (equipment) {
                [equipments addObject:equipment];
            }
        }
        [db closeOpenResultSets];
    }];
    return equipments;
}
//#pragma mark - mission_location_rel table
///**
// *  名称	任务位置关系表 mission_location_rel
// */
//- (BOOL)createMissionLocationRelTable
//{
//    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'mission_location_rel' (missionId integer NOT NULL,locationId integer,siteId integer,siteType smallint,equipmentTypeId integer);";
//    return [_fmdb executeUpdate:sql];
//}

#pragma mark - handler table
NSString *const KSqlCreateHandlerTable = @"CREATE TABLE IF NOT EXISTS 'handler' (uniqueId integer NOT NULL,userName varchar(200),headIcon varchar(200),mobile varchar(200));";

- (BOOL)createHandlerTable
{
    return [_fmdb executeUpdate:KSqlCreateHandlerTable];
}

- (void)dropAndReCreateHandlerTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists handler;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateHandlerTable];
        }
    }];
}

#pragma mark - WeChatPostTroubleReporterTable
NSString *const KSqlCreateWeChatPostTroubleReporterTable = @"CREATE TABLE IF NOT EXISTS 'weChatPostTroubleReporter' (troubleId integer NOT NULL,contactName varchar(200),contactNo varchar(200));";

- (BOOL)createWeChatPostTroubleReporterTable{
    return [_fmdb executeUpdate:KSqlCreateWeChatPostTroubleReporterTable];
}

#pragma mark - handlerAndBuildingRelTable
NSString *const KSqlCreateHandlerAndBuildingRelTable = @"CREATE TABLE IF NOT EXISTS 'YW_handler_building_rel' (buildingId varchar,uniqueId integer);";

- (BOOL)createHandlerAndBuildingRelTable{
    return [_fmdb executeUpdate:KSqlCreateHandlerAndBuildingRelTable];
}

#pragma mark - organizationTable
NSString *const KSqlCreateOrganizationTable = @"CREATE TABLE IF NOT EXISTS 'YW_Organization' (organizationNo varchar NOT NULL UNIQUE,organizationName varchar,simpleName varchar, organizationLogoUrl varchar);";

- (BOOL)createOrganizationTable{
    return [_fmdb executeUpdate:KSqlCreateOrganizationTable];
}

#pragma mark - organizationAndDepartmentsRelTable
- (void)dropOrganizationAndHandlerRelTable{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"drop table if exists YW_Organization_Handler_rel;";
        [db executeUpdate:sql];
        sql = @"drop table if exists YW_Organization;";
        if ([db executeUpdate:sql]) {
            [db executeUpdate:KSqlCreateOrganizationTable];
        }
    }];
    
}
NSString *const KSqlCreateOrganizationAndDepartmentsRelTable = @"CREATE TABLE IF NOT EXISTS 'YW_Organization_Departments_rel' (organizationNo varchar,departmentId integer);";

- (BOOL)createOrganizationAndDepartmentsRelTable{
    return [_fmdb executeUpdate:KSqlCreateOrganizationAndDepartmentsRelTable];
}

- (BOOL)saveBuildingMembersWithJson:(NSArray *)buildingMembersJsonArray{
    if (buildingMembersJsonArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    __block NSMutableArray *departmentArray = [NSMutableArray array];
    __block NSMutableArray *allHandersArray = [NSMutableArray array];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        //删除
        sql = @"DELETE FROM 'YW_handler_building_rel' ";
        executeResult = [db executeUpdate:sql];
        
        //删除
        sql = @"delete FROM 'YW_Organization_Departments_rel'";
        executeResult = [db executeUpdate:sql];
        if (!executeResult) {
            *rollback = YES;
        }
        [buildingMembersJsonArray enumerateObjectsUsingBlock:^(YWProjectMembersJson* _Nonnull memberJson, NSUInteger idx, BOOL* _Nonnull stop) {
            
            [allHandersArray addObjectsFromArray:memberJson.members];
            
            [memberJson.members enumerateObjectsUsingBlock:^(YWHandler*  _Nonnull handler, NSUInteger idx, BOOL * _Nonnull stop) {
                //更新handler和building表
                sql = @"SELECT * FROM 'YW_handler_building_rel' WHERE buildingId=? AND uniqueId=?";
                FMResultSet* set = [db executeQuery:sql, memberJson.buildingId,@(handler.uniqueId)];
                if (![set next]) {
                    sql = @"INSERT INTO 'YW_handler_building_rel' (buildingId,uniqueId) VALUES (?, ?)";
                    executeResult = [db executeUpdate:sql, memberJson.buildingId,@(handler.uniqueId)];
                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    };
                }
                
                //更新未分配的部门和组织机构的关系
                sql = @"SELECT * FROM 'YW_Organization_Departments_rel' WHERE organizationNo=? AND departmentId=?";
                set = [db executeQuery:sql, handler.organization.organizationNo,@(-[handler.organization.organizationNo integerValue])];
                if (![set next]) {
                    sql = @"INSERT INTO 'YW_Organization_Departments_rel' (organizationNo,departmentId) VALUES (?, ?)";
                    executeResult = [db executeUpdate:sql, handler.organization.organizationNo,@(-[handler.organization.organizationNo integerValue])];
                    //添加未分配部门
                    sql = @"INSERT INTO 'departments' (departmentId,departmentName) VALUES (?, ?);";
                    executeResult = [db executeUpdate:sql, @(-[handler.organization.organizationNo integerValue]), @"未分配部门"];
                    if (!executeResult) {
                        *rollback = YES;
                    }
                }
                [handler.departments enumerateObjectsUsingBlock:^(YWDepartment*  _Nonnull department, NSUInteger idx, BOOL * _Nonnull stop) {
                    sql = @"SELECT * FROM 'YW_Organization_Departments_rel' WHERE organizationNo=? AND departmentId=?";
                    FMResultSet* set = [db executeQuery:sql, handler.organization.organizationNo,@(department.departmentId)];
                    if (![set next]) {
                        sql = @"INSERT INTO 'YW_Organization_Departments_rel' (organizationNo,departmentId) VALUES (?, ?)";
                        executeResult = [db executeUpdate:sql, handler.organization.organizationNo,@(department.departmentId)];
                        if (!executeResult) {
                            *stop = YES;
                            *rollback = YES;
                        };
                    }
                }];
                
                //更新组织机构表
                sql = @"SELECT * FROM 'YW_Organization' WHERE organizationNo=?;";
                set = [db executeQuery:sql, handler.organization.organizationNo];
                if ([set next]) {
                    sql = @"UPDATE 'YW_Organization' SET organizationName=? where organizationNo=?";
                    executeResult = [db executeUpdate:sql,handler.organization.organizationName,handler.organization.organizationNo];
                }else{
                    sql = @"INSERT INTO 'YW_Organization' (organizationNo,organizationName) VALUES (?, ?);";
                    executeResult = [db executeUpdate:sql, handler.organization.organizationNo, handler.organization.organizationName];
                }
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                };
                
                //更新handler
                sql = @"SELECT * FROM 'handler' WHERE uniqueId=?;";
                set = [db executeQuery:sql, @(handler.uniqueId)];
                if ([set next]) {
                    sql = @"UPDATE 'handler' SET userName =?,headIcon=?,mobile=? WHERE uniqueId =?;";
                    executeResult = [db executeUpdate:sql, handler.userName, handler.headIcon, handler.mobile, @(handler.uniqueId)];
                }else {
                    sql = @"INSERT INTO 'handler' (uniqueId,userName,headIcon,mobile) VALUES (?, ?, ? ,?);";
                    executeResult = [db executeUpdate:sql, @(handler.uniqueId), handler.userName, handler.headIcon, handler.mobile];
                }
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                };
                [departmentArray addObjectsFromArray:handler.departments];
                
            }];
            
        }];
        [db closeOpenResultSets];
    }];
    [self updateDepartmentsWithArray:departmentArray needDelete:YES];
    [self updateDepartmentAndHandlerRelation:allHandersArray needDelete:YES];
    return executeResult;
}

- (BOOL)saveOrganizationMembersWithArray:(NSArray *)organizationMembers{
    if (organizationMembers.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    __block NSMutableArray *departmentArray = [NSMutableArray array];
    
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        
        [organizationMembers enumerateObjectsUsingBlock:^(YWHandler* _Nonnull handler, NSUInteger idx, BOOL* _Nonnull stop) {
            //更新未分配的部门和组织机构的关系
            sql = @"SELECT * FROM 'YW_Organization_Departments_rel' WHERE organizationNo=? AND departmentId=?";
            FMResultSet* set = [db executeQuery:sql, handler.organization.organizationNo,@(-[handler.organization.organizationNo integerValue])];
            if (![set next]) {
                sql = @"INSERT INTO 'YW_Organization_Departments_rel' (organizationNo,departmentId) VALUES (?, ?)";
                executeResult = [db executeUpdate:sql, handler.organization.organizationNo,@(-[handler.organization.organizationNo integerValue])];
                //添加未分配部门
                sql = @"INSERT INTO 'departments' (departmentId,departmentName) VALUES (?, ?);";
                executeResult = [db executeUpdate:sql, @(-[handler.organization.organizationNo integerValue]), @"未分配部门"];
                if (!executeResult) {
                    *rollback = YES;
                }
            }
            //更新department和organization关系表
            [handler.departments enumerateObjectsUsingBlock:^(YWDepartment*  _Nonnull department, NSUInteger idx, BOOL * _Nonnull stop) {
                sql = @"SELECT * FROM 'YW_Organization_Departments_rel' WHERE organizationNo=? AND departmentId=?";
                FMResultSet* set = [db executeQuery:sql, handler.organization.organizationNo,@(department.departmentId)];
                if (![set next]) {
                    sql = @"INSERT INTO 'YW_Organization_Departments_rel' (organizationNo,departmentId) VALUES (?, ?)";
                    executeResult = [db executeUpdate:sql, handler.organization.organizationNo,@(department.departmentId)];
                    if (!executeResult) {
                        *stop = YES;
                        *rollback = YES;
                    };
                }
            }];
            //更新组织机构表
            sql = @"SELECT * FROM 'YW_Organization' WHERE organizationNo=?;";
            set = [db executeQuery:sql, handler.organization.organizationNo];
            if ([set next]) {
                sql = @"UPDATE 'YW_Organization' SET organizationName=? where organizationNo=?";
                executeResult = [db executeUpdate:sql,handler.organization.organizationName,handler.organization.organizationNo];
            }else {
                sql = @"INSERT INTO 'YW_Organization' (organizationNo,organizationName) VALUES (?, ?);";
                executeResult = [db executeUpdate:sql, handler.organization.organizationNo, handler.organization.organizationName];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            //更新handler
            sql = @"SELECT * FROM 'handler' WHERE uniqueId=?;";
            set = [db executeQuery:sql, @(handler.uniqueId)];
            if ([set next]) {
                sql = @"UPDATE 'handler' SET userName =?,headIcon=?,mobile=? WHERE uniqueId =?;";
                executeResult = [db executeUpdate:sql, handler.userName, handler.headIcon, handler.mobile, @(handler.uniqueId)];
            }else {
                sql = @"INSERT INTO 'handler' (uniqueId,userName,headIcon,mobile) VALUES (?, ?, ? ,?);";
                executeResult = [db executeUpdate:sql, @(handler.uniqueId), handler.userName, handler.headIcon, handler.mobile];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            [departmentArray addObjectsFromArray:handler.departments];
        }];

        [db closeOpenResultSets];
    }];
    [self updateDepartmentsWithArray:departmentArray needDelete:NO];
    [self updateDepartmentAndHandlerRelation:organizationMembers needDelete:NO];
    return executeResult;
}

- (BOOL)updateHandlerWithArray:(NSArray*)handlerArray{
    //只更新了handler，不更新部门以及部门和人的表
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [handlerArray enumerateObjectsUsingBlock:^(YWHandler* _Nonnull handler, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'handler' WHERE uniqueId=?;";
            FMResultSet* set = [db executeQuery:sql, @(handler.uniqueId)];
            if ([set next]) {
                if (handler.userName.length>0 && handler.headIcon.length>0 && handler.mobile.length>0) {
                    NSString *newSql = sql = @"UPDATE 'handler' SET userName=?,headIcon=?,mobile=? WHERE uniqueId=?;";
                    executeResult = [db executeUpdate:newSql, handler.userName, handler.headIcon, handler.mobile, @(handler.uniqueId)];
                }else if (handler.userName.length>0 && handler.headIcon.length>0){
                    NSString *newSql = sql = @"UPDATE 'handler' SET userName=?,headIcon=? WHERE uniqueId=?;";
                    executeResult = [db executeUpdate:newSql, handler.userName, handler.headIcon, @(handler.uniqueId)];
                }else if (handler.userName.length>0){
                    NSString *newSql = sql = @"UPDATE 'handler' SET userName=? WHERE uniqueId=?;";
                    executeResult = [db executeUpdate:newSql, handler.userName,@(handler.uniqueId)];
                }
            }
            else {
                sql = @"INSERT INTO 'handler' (uniqueId,userName,headIcon,mobile) VALUES (?, ?, ? ,?);";
                executeResult = [db executeUpdate:sql, @(handler.uniqueId), handler.userName, handler.headIcon, handler.mobile];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];

        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (YWHandler*)handlerWithSet:(FMResultSet*)set
{
    YWHandler* handler = [[YWHandler alloc] init];
    handler.uniqueId = [set intForColumn:@"uniqueId"];
    handler.headIcon = [set stringForColumn:@"headIcon"];
    handler.userName = [set stringForColumn:@"userName"];
    handler.mobile = [set stringForColumn:@"mobile"];
    return handler;
}

- (NSArray*)allHandler
{
    __block NSMutableArray* handlers = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        //        NSString* sql = @"SELECT * FROM 'handler';";
        NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId IN (SELECT uniqueId FROM 'departments_handler_rel');";
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWHandler* handler = [self handlerWithSet:set];
            [handlers addObject:handler];
        }
        [db closeOpenResultSets];
    }];
    return handlers;
}


//#pragma mark - lastMaintenance_time table
///**
// *  名称 设备上一次维保时间表 lastMaintenance_time
// */
//- (BOOL)createLastMaintenanceTimeTable
//{
//    NSString* sql = @"CREATE TABLE 'lastMaintenance_time' (equipmentId varchar(23) NOT NULL,maintenanceDate timestamp,maintenanceTypeId integer,executorName varchar(50));";
//    return [_fmdb executeUpdate:sql];
//}
//
//- (BOOL)saveLastMaintenanceTimeWithArray:(NSArray*)lastMaintenanceTimeArray
//{
//    __block BOOL executeResult = YES;
//    __block NSString* sql = nil;
//    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
//        sql = @"DELETE FROM 'lastMaintenance_time';";
//        executeResult = [db executeUpdate:sql];
//        if (!executeResult) {
//            *rollback = YES;
//        }
//
//        __block BOOL blockStopAll = NO;
//        [lastMaintenanceTimeArray enumerateObjectsUsingBlock:^(YWLastMaintenanceTime* _Nonnull lastMaintenanceTime, NSUInteger idx, BOOL* _Nonnull stop) {
//
//            sql = @"INSERT INTO 'lastMaintenance_time' (equipmentId,maintenanceDate,maintenanceTypeId,executorName) VALUES (?, ?, ?,?);";
//            executeResult = [db executeUpdate:sql, lastMaintenanceTime.equipmentId, @(lastMaintenanceTime.maintenanceDate), @(lastMaintenanceTime.maintenanceTypeId), lastMaintenanceTime.executorName];
//            if (!executeResult) {
//                *stop = YES;
//                blockStopAll = YES;
//                *rollback = YES;
//            }
//        }];
//        [db closeOpenResultSets];
//    }];
//    return executeResult;
//}
//
//- (YWLastMaintenanceTime*)lastMaintenanceTimeWithEquipmentId:(NSString*)equipmentId
//{
//    __block YWLastMaintenanceTime* lastMaintenanceTime = nil;
//    [self.dbQeue inDatabase:^(FMDatabase* db) {
//        NSString* sql = @"SELECT * FROM 'lastMaintenance_time' WHERE equipmentId = ?;";
//        FMResultSet* set = [db executeQuery:sql, equipmentId];
//
//        if ([set next]) {
//            lastMaintenanceTime = [[YWLastMaintenanceTime alloc] init];
//            lastMaintenanceTime.equipmentId = [set stringForColumn:@"equipmentId"];
//            lastMaintenanceTime.maintenanceDate = [set longLongIntForColumn:@"maintenanceDate"];
//            lastMaintenanceTime.maintenanceTypeId = [set intForColumn:@"maintenanceTypeId"];
//            lastMaintenanceTime.executorName = [set stringForColumn:@"executorName"];
//        }
//        [db closeOpenResultSets];
//    }];
//    return lastMaintenanceTime;
//}
//
//- (BOOL)updateLastMaintenanceTimeWithEquipments:(NSArray*)equipments maintenceTime:(NSTimeInterval)maintenceTime executorName:(NSString*)executorName
//{
//    __block BOOL executeResult = YES;
//    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
//        __block NSString* sql = nil;
//        [equipments enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL* _Nonnull stop) {
//
//            sql = @"SELECT * FROM 'lastMaintenance_time' WHERE equipmentId=?;";
//            FMResultSet* set = [db executeQuery:sql, equipment.equipmentId];
//
//            if ([set next]) {
//                sql = @"UPDATE 'lastMaintenance_time' SET maintenanceDate=?,executorName=? WHERE equipmentId = ?;";
//                executeResult = [db executeUpdate:sql, @(maintenceTime), executorName, equipment.equipmentId];
//            }
//            else {
//                sql = @"INSERT INTO 'lastMaintenance_time' (equipmentId,maintenanceDate,maintenanceTypeId,executorName) VALUES (?, ?, ?,?);";
//                executeResult = [db executeUpdate:sql, equipment.equipmentId, @(maintenceTime), @(YWMaintenanceTypeDetection), executorName];
//            }
//
//            if (!executeResult) {
//                *stop = YES;
//                *rollback = YES;
//            };
//        }];
//        [db closeOpenResultSets];
//    }];
//    return executeResult;
//}

//#pragma mark - createLocationQrcodeRelTable table
///**
// *  名称 二维码编号与位置Id关系表 location_qrcode_rel
// */
//- (BOOL)createLocationQrcodeRelTable
//{
//    NSString* sql = @"CREATE TABLE 'location_qrcode_rel' (qrcodeId varchar(19) NOT NULL UNIQUE,locationId integer NOT NULL);";
//    return [_fmdb executeUpdate:sql];
//}

- (NSInteger)locationIdWithQrcodeId:(NSString*)qrcodeId
{
    __block NSInteger locationId = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        //        NSString* sql = @"SELECT * FROM 'location_qrcode_rel' WHERE qrcodeId=?;";
        NSString* sql = @"SELECT locationId FROM 'equipment' WHERE qrcodeId=?;";
        FMResultSet* set = [db executeQuery:sql, qrcodeId];
        if ([set next]) {
            locationId = [set intForColumn:@"locationId"];
        }
        [db closeOpenResultSets];
    }];
    return locationId;
}

#pragma mark - 巡更,巡查,抄表等记录的图片表
- (BOOL)createPatrolPointPictureTable
{
    NSString* sql = @"CREATE TABLE 'record_picture' (recordId varchar(30),pictureId varchar(30),pictureName varchar(200),isLocalImage boolean DEFAULT 0,uploadStatus integer,bigUrl varchar(200),smallUrl varchar(200),recordType integer);";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)updatePatrolPictureWithArray:(NSArray*)patrolPictures
{
    if (patrolPictures.count==0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockPatrolPictures = patrolPictures;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockPatrolPictures enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull patrolPicture, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString* sql = @"SELECT  * FROM 'record_picture' WHERE pictureId=?";
            FMResultSet* set = [db executeQuery:sql, patrolPicture.pictureId];
            if ([set next]) {
                sql = @"UPDATE 'record_picture' SET pictureName=?,isLocalImage=?,uploadStatus=?,bigUrl=?, smallUrl =? ,recordId =? ,recordType=? WHERE pictureId=?;";
                executeResult = [db executeUpdate:sql, patrolPicture.pictureName, @(patrolPicture.isLocalImage), @(patrolPicture.uploadStatus), patrolPicture.bigUrl, patrolPicture.smallUrl, patrolPicture.recordId, @(patrolPicture.recordType), patrolPicture.pictureId];
            }
            else {
                sql = @"INSERT INTO 'record_picture' (pictureId,pictureName,isLocalImage,uploadStatus,recordId ,bigUrl ,smallUrl,recordType) VALUES (?,?, ?, ?,?,?,?,?);";
                executeResult = [db executeUpdate:sql, patrolPicture.pictureId, patrolPicture.pictureName, @(patrolPicture.isLocalImage), @(patrolPicture.uploadStatus), patrolPicture.recordId, patrolPicture.bigUrl, patrolPicture.smallUrl, @(patrolPicture.recordType)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updatePatrolPictureWithNewWorkData:(NSArray*)patrolPictures
{
    if (patrolPictures.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockPatrolPictures = patrolPictures;
    __block NSString* sql = nil;
    NSMutableArray* recordIdsArray = [NSMutableArray array];
    [patrolPictures enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull patrolPicture, NSUInteger idx, BOOL* _Nonnull stop) {
        if (![recordIdsArray containsObject:patrolPicture.recordId]) {
            [recordIdsArray addObject:patrolPicture.recordId];
        }
    }];
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [recordIdsArray enumerateObjectsUsingBlock:^(NSString* _Nonnull recordId, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"delete FROM 'record_picture' WHERE recordId=?;";
            executeResult = [db executeUpdate:sql, recordId];
            if (!executeResult) {
                *rollback = YES;
            }
        }];
        if (executeResult) {
            [blockPatrolPictures enumerateObjectsUsingBlock:^(YWPatrolPicture* _Nonnull patrolPicture, NSUInteger idx, BOOL* _Nonnull stop) {
                sql = @"INSERT INTO 'record_picture' (pictureId,pictureName,isLocalImage,uploadStatus,recordId ,bigUrl ,smallUrl,recordType) VALUES (?,?, ?, ?,?,?,?,?);";
                BOOL result = [db executeUpdate:sql, patrolPicture.pictureId, patrolPicture.pictureName, @(patrolPicture.isLocalImage), @(patrolPicture.uploadStatus), patrolPicture.recordId, patrolPicture.bigUrl, patrolPicture.smallUrl, @(patrolPicture.recordType)];
                if (!result) {
                    *stop = YES;
                    *rollback = YES;
                    executeResult = NO;
                };
            }];
        }
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updatePatrolPictureRecordId:(NSString*)recordId WithOldRecordId:(NSString*)ordRecordId
{
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        sql = @"SELECT * FROM 'record_picture' WHERE recordId=?;";
        FMResultSet* set = [db executeQuery:sql,ordRecordId];
        if ([set next]) {
            sql = @"UPDATE 'record_picture' SET recordId =? WHERE recordId =?;";
            executeResult = [db executeUpdate:sql, recordId, ordRecordId];
        }
        if (!executeResult) {
            *rollback = YES;
        };
        
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray*)recordPictureWithRecordId:(NSString*)recordId recordType:(NSInteger)recordType
{
    __block NSMutableArray* pictures = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'record_picture' WHERE recordId=? AND recordType=?";
        FMResultSet* set = [db executeQuery:sql, recordId, @(recordType)];
        while ([set next]) {
            if (pictures.count<6) {
                YWPatrolPicture* picture = [[YWPatrolPicture alloc] init];
                picture.recordId = [set stringForColumn:@"recordId"];
                picture.pictureId = [set stringForColumn:@"pictureId"];
                picture.pictureName = [set stringForColumn:@"pictureName"];
                picture.isLocalImage = [set intForColumn:@"isLocalImage"];
                picture.uploadStatus = [set intForColumn:@"uploadStatus"];
                picture.bigUrl = [set stringForColumn:@"bigUrl"];
                picture.smallUrl = [set stringForColumn:@"smallUrl"];
                picture.recordType = [set intForColumn:@"recordType"];
                [pictures addObject:picture];
            }
        }
        [db closeOpenResultSets];
    }];
    return pictures;
}



- (YWHandler*)handlerWithUniqueId:(NSInteger)uniqueId
{
    __block YWHandler* handler = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId=?;";
        FMResultSet* set = [db executeQuery:sql, @(uniqueId)];
        while ([set next]) {
            handler = [self handlerWithSet:set];
        }
        [db closeOpenResultSets];
    }];
    return handler;
}

#pragma mark - 附件
/**
 *  名称 附件 attachment
 */
- (BOOL)createAttachmentTable
{
    NSString* sql = @"CREATE TABLE 'attachment' (attachmentId integer UNIQUE, attachmentName text, fileSize integer, downLoadUrl text, localName text, recordId text, attachmentType integer);";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)updateAttachmentWithAttachments:(NSArray*)attachments
{
    if (attachments.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockAttachments = attachments;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockAttachments enumerateObjectsUsingBlock:^(YWattachment* _Nonnull attachment, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'attachment' WHERE attachmentId=? AND attachmentType=?;";
            FMResultSet* set = [db executeQuery:sql, @(attachment.attachmentId), @(attachment.attachmentType)];
            //不更新localPath
            if ([set next]) {
                sql = @"UPDATE 'attachment' SET  attachmentName=? ,fileSize =?,downLoadUrl =? ,recordId=? WHERE attachmentId=? AND attachmentType=?;";
                executeResult = [db executeUpdate:sql, attachment.attachmentName, @(attachment.fileSize), attachment.downLoadUrl, @(attachment.recordId), @(attachment.attachmentId), @(attachment.attachmentType)];
            }
            else {
                sql = @"INSERT INTO 'attachment' (attachmentId, attachmentName, fileSize, downLoadUrl, localName, recordId, attachmentType) VALUES (?, ?, ?, ?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql, @(attachment.attachmentId), attachment.attachmentName, @(attachment.fileSize), attachment.downLoadUrl, attachment.localName, @(attachment.recordId), @(attachment.attachmentType)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (BOOL)updateAttachmenLocalNameWithAttachment:(YWattachment*)attachment
{
    __block BOOL executeResult = YES;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"UPDATE 'attachment' SET localName=? WHERE attachmentId=? AND recordId=?;";
        executeResult = [db executeUpdate:sql, attachment.localName, @(attachment.attachmentId), @(attachment.recordId)];
        [db closeOpenResultSets];
    }];
    return executeResult;
}
- (NSArray*)attachmentWithRecordId:(NSInteger)recordId andType:(YWattachmentType)type
{
    __block NSMutableArray* blockAttachments = [NSMutableArray array];
    __block NSString* sql = @"";
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        sql = @"SELECT * FROM 'attachment' where recordId=? AND attachmentType=?;";
        FMResultSet* set = [db executeQuery:sql, @(recordId), @(type)];
        while ([set next]) {
            YWattachment* attachment = [self attachmentWithFMResultSet:set];
            [blockAttachments addObject:attachment];
        }
        [db closeOpenResultSets];
    }];

    return blockAttachments.count ? blockAttachments : nil;
}
- (YWattachment*)attachmentWithFMResultSet:(FMResultSet*)set
{
    YWattachment* attachment = [[YWattachment alloc] init];
    attachment.attachmentId = [set intForColumn:@"attachmentId"];
    attachment.attachmentName = [set stringForColumn:@"attachmentName"];
    attachment.fileSize = [set intForColumn:@"fileSize"];
    attachment.downLoadUrl = [set stringForColumn:@"downLoadUrl"];
    attachment.localName = [set stringForColumn:@"localName"];
    attachment.recordId = [set intForColumn:@"recordId"];
    attachment.attachmentType = [set intForColumn:@"attachmentType"];
    return attachment;
}



#pragma mark - 消息
//- (BOOL)createMessageTable
//{
//    NSString* sql = @"CREATE TABLE 'message' (sessionId text NOT NULL,sessionType smallint,sessionName text,messageId text NOT NULL,messageType smallint,message text,title text,toUserId integer,fromUserId integer,createTime timestamp,status smallint,isRead boolean DEFAULT 0,relationId text,relationType smallint);";
//    return [_fmdb executeUpdate:sql];
//}


#pragma mark - 部门
/**
 *  名称 部门 departments
 */
- (BOOL)createDepartmentsTable
{
    NSString* sql = @"CREATE TABLE 'departments' (departmentId integer NOT NULL,departmentName text);";
    return [_fmdb executeUpdate:sql];
}
#pragma mark - 部门与人的关系
/**
 *  名称 部门与人的关系表 departments_handler_rel
 */
- (BOOL)createDepartmentsAndHandlerTable
{
    NSString* sql = @"CREATE TABLE 'departments_handler_rel' (departmentId integer,uniqueId integer);";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)updateDepartmentsWithArray:(NSArray*)departmentArray needDelete:(BOOL)neddDelete
{
    if (departmentArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockDepartmentArray = departmentArray;
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        if (neddDelete) {
            sql = @"DELETE FROM 'departments' where departmentId>0";
            executeResult = [db executeUpdate:sql];
            if (!executeResult) {
                *rollback = YES;
            }
        }

        [blockDepartmentArray enumerateObjectsUsingBlock:^(YWDepartmentJson* _Nonnull departmentJson, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'departments' WHERE departmentId=?;";
            FMResultSet* set = [db executeQuery:sql, @(departmentJson.departmentId)];
            if ([set next]) {
                sql = @"UPDATE 'departments' SET departmentName =? WHERE departmentId =?;";
                executeResult = [db executeUpdate:sql, departmentJson.departmentName, @(departmentJson.departmentId)];
            }else {
                sql = @"INSERT INTO 'departments' (departmentId,departmentName) VALUES (?, ?);";
                executeResult = [db executeUpdate:sql, @(departmentJson.departmentId), departmentJson.departmentName];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (BOOL)updateDepartmentAndHandlerRelation:(NSArray*)handlerArray needDelete:(BOOL)needDelete{
    if (handlerArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSString* sql = nil;
//    __block NSMutableArray *departmentIdArray = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        if (needDelete) {
            sql = @"DELETE FROM 'departments_handler_rel'";
            executeResult = [db executeUpdate:sql];
//            departmentIdArray= [NSMutableArray array];
        }
        [handlerArray enumerateObjectsUsingBlock:^(YWHandler* _Nonnull handler, NSUInteger idx, BOOL* _Nonnull stop) {
            if (handler.departments.count) {
                [handler.departments enumerateObjectsUsingBlock:^(YWDepartmentJson* _Nonnull departmentJson, NSUInteger idx, BOOL* _Nonnull stop) {
//                    if (needDelete && ![departmentIdArray containsObject:@(departmentJson.departmentId)]) {
//                        [departmentIdArray addObject:@(departmentJson.departmentId)];
//                        sql = @"DELETE FROM 'departments_handler_rel' where departmentId=?";
//                        executeResult = [db executeUpdate:sql,@(departmentJson.departmentId)];
//                    }
                    
                    sql = @"select * from 'departments_handler_rel' where departmentId=? AND uniqueId=?";
                    FMResultSet *set = [db executeQuery:sql, @(departmentJson.departmentId), @(handler.uniqueId)];
                    if (![set next]) {
                        sql = @"INSERT INTO 'departments_handler_rel' (departmentId,uniqueId) VALUES (?, ?);";
                        executeResult = [db executeUpdate:sql, @(departmentJson.departmentId), @(handler.uniqueId)];
                        if (!executeResult) {
                            *stop = YES;
                            *rollback = YES;
                        };
                    }
                    
                }];
            }else {
                sql = @"INSERT INTO 'departments_handler_rel' (departmentId,uniqueId) VALUES (?, ?);";
                executeResult = [db executeUpdate:sql, @(-[handler.organization.organizationNo integerValue]), @(handler.uniqueId)];
                if (!executeResult) {
                    *stop = YES;
                    *rollback = YES;
                };
            }
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSArray*)allDepartments{
    __block NSMutableArray* departmentArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'departments' where departmentId>0 ORDER BY departmentId;";
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWDepartment* department = [self departmentWithSet:set db:db];;
            [departmentArray addObject:department];
        }
        [db closeOpenResultSets];
    }];
    return departmentArray;
}

- (NSArray *)departmentWithHandlersByOrganizationNo:(NSString *)organizationNo{
    __block NSMutableArray* departmentArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
//        NSString *sql = @"SELECT * from departments where departmentId in (select distinct departmentId from YW_Organization_Departments_rel where organizationNo=?) order by departmentId";
        NSString *sql = [NSString stringWithFormat:@"select distinct d.* from 'departments' d left join 'YW_Organization_Departments_rel' r on d.departmentId = r.departmentId where r.organizationNo='%@' order by d.departmentId",organizationNo];
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWDepartment* department = [self departmentWithSet:set db:db];;
            [departmentArray addObject:department];
            
            NSMutableArray* memberArray = [NSMutableArray array];
            NSString *handlerSql = [NSString stringWithFormat:@"select distinct h.* from 'handler' h left join 'departments_handler_rel' d on d.uniqueId = h.uniqueId where d.departmentId=%ld",(long)department.departmentId];
            FMResultSet* handlerSet = [db executeQuery:handlerSql];
            while ([handlerSet next]) {
                YWHandler* handler = [self handlerWithSet:handlerSet];
                [memberArray addObject:handler];
            }
            department.memberArray = memberArray;
        }
        [db closeOpenResultSets];
    }];
    return departmentArray;
}

- (NSArray*)departmentWithHandlersByBuildingId:(NSString *)buildingId{
    __block NSMutableArray* departmentArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
//        NSString* sql = @"select * from departments where departmentId in (select distinct departmentId from departments_handler_rel where uniqueId in (select uniqueId from YW_handler_building_rel where buildingId =?)) ORDER BY departmentId";
        NSString *sql = [NSString stringWithFormat:@"select distinct d.* from 'departments' d left join 'departments_handler_rel' r on d.departmentId = r.departmentId left join 'YW_handler_building_rel' b on b.uniqueId = r.uniqueId left join 'YW_Organization_Departments_rel' o on d.departmentId = o.departmentId where b.buildingId='%@' ORDER BY o.organizationNo,d.departmentId",buildingId];
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWDepartment* department = [self departmentWithSet:set db:db];
            [departmentArray addObject:department];
            
            NSMutableArray* memberArray = [NSMutableArray array];
            NSString* handlerSql = [NSString stringWithFormat:@"select distinct h.* from 'handler' h left join 'YW_handler_building_rel' b on h.uniqueId = b.uniqueId left join 'departments_handler_rel' d on d.uniqueId = b.uniqueId where d.departmentId=%ld AND b.buildingId='%@'",(long)department.departmentId,buildingId];
            FMResultSet* handlerSet = [db executeQuery:handlerSql];
            while ([handlerSet next]) {
                YWHandler* handler = [self handlerWithSet:handlerSet];
                [memberArray addObject:handler];
            }
            
            department.memberArray = memberArray;
        }
        [db closeOpenResultSets];
    }];
    return departmentArray;
}

- (YWDepartment *)departmentWithSet:(FMResultSet*)set db:(FMDatabase* )db{
    YWDepartment* department = [[YWDepartment alloc] init];
    department.departmentId = [set intForColumn:@"departmentId"];
    department.departmentName = [set stringForColumn:@"departmentName"];
    //查询部门所属的机构
    NSString * sql = @"select * from YW_Organization where organizationNo = (select organizationNo from YW_Organization_Departments_rel where departmentId=?) ";
    FMResultSet* orgSet = [db executeQuery:sql, @(department.departmentId)];
    if ([orgSet next]) {
        department.organization = [self organizationWithSet:orgSet db:db];
        department.organizationNo = department.organization.organizationNo;
    }
    return department;
}

- (YWOrganization *)organizationWithSet:(FMResultSet*)set db:(FMDatabase* )db{
    YWOrganization *organization = [[YWOrganization alloc] init];
    organization.organizationNo = [set stringForColumn:@"organizationNo"];
    organization.organizationName = [set stringForColumn:@"organizationName"];
//    YWOrganizationPicture *logo = [[YWOrganizationPicture alloc] init];
//    logo.url = [set stringForColumn:@"organizationLogoUrl"];
//    organization.organizationLogo = logo;
    organization.simpleName = [set stringForColumn:@"simpleName"];
    return organization;
}

- (NSArray *)handlerWithDepartmentIds:(NSString *)departmentIds{
    if (departmentIds.length==0) {
        return nil;
    }
    __block NSMutableArray* handlers = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = [NSString stringWithFormat:@"SELECT * FROM 'departments_handler_rel' WHERE departmentId in (%@)",departmentIds];
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            NSInteger uniqueId = [set intForColumn:@"uniqueId"];
            NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId=?;";
            FMResultSet* handlerSet = [db executeQuery:sql, @(uniqueId)];
            if ([handlerSet next]) {
                YWHandler* handler = [self handlerWithSet:handlerSet];
                [handlers addObject:handler];
            }
        }
        [db closeOpenResultSets];
    }];
    return handlers;
}
- (YWHandler*)getHandlerWithUniqueId:(NSInteger)uniqueId{
    __block YWHandler* handler;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'handler' WHERE uniqueId = ?;";
        FMResultSet* set = [db executeQuery:sql,@(uniqueId)];
        if ([set next]) {
            handler = [self handlerWithSet:set];
        }
        [db closeOpenResultSets];
    }];
    return handler;
}
#pragma mark - 资料库
/**
 *  名称 资料库表 informationBank
 */
- (BOOL)createInformationBankTable
{
    NSString* sql = @"CREATE TABLE 'informationBank' (infoId integer,typeId integer,name text,buildingId text,creatorId integer,createTime timestamp,attachmentId integer,status smallint DEFAULT 1);";
    return [_fmdb executeUpdate:sql];
}
- (BOOL)saveInformationWithArray:(NSArray*)informationArray
{
    if (informationArray.count == 0) {
        return YES;
    }
    __block BOOL executeResult = YES;
    __block NSArray* blockInformationArray = informationArray;
    __block NSMutableArray* blockAttachmentArray = [NSMutableArray array];
    __block NSString* sql = nil;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [blockInformationArray enumerateObjectsUsingBlock:^(YWInformationBankModel* _Nonnull infoModel, NSUInteger idx, BOOL* _Nonnull stop) {
            sql = @"SELECT * FROM 'informationBank' WHERE infoId=? AND typeId=?;";
            FMResultSet* set = [db executeQuery:sql, @(infoModel.infoId), @(infoModel.typeId)];
            if ([set next]) {
                sql = @"UPDATE 'informationBank' SET name=?,buildingId=?,creatorId=?,createTime=?,attachmentId=? WHERE infoId=? AND typeId=?;";
                executeResult = [db executeUpdate:sql, infoModel.name, infoModel.buildingId, @(infoModel.creator.uniqueId), @(infoModel.createTime), @(infoModel.attachment.attachmentId), @(infoModel.infoId), @(infoModel.typeId)];
            }
            else {
                sql = @"INSERT INTO 'informationBank' (infoId,typeId,name,buildingId,creatorId,createTime,attachmentId) VALUES (?, ?, ?, ?, ?, ?, ?);";
                executeResult = [db executeUpdate:sql, @(infoModel.infoId), @(infoModel.typeId), infoModel.name, infoModel.buildingId, @(infoModel.creator.uniqueId), @(infoModel.createTime), @(infoModel.attachment.attachmentId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
            [blockAttachmentArray addObject:infoModel.attachment];
        }];
        [db closeOpenResultSets];
    }];
    //保存资料的附件
    [self updateAttachmentWithAttachments:blockAttachmentArray];
    return executeResult;
}

- (NSArray*)informationArrayWithPage:(NSInteger)page
{
    __block NSInteger showCount = page * 10;
    __block NSMutableArray* allInformationArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = [NSString stringWithFormat:@"SELECT * FROM 'informationBank' order by createTime desc LIMIT %ld;", (long)showCount];
        FMResultSet* set = [db executeQuery:sql];
        while ([set next]) {
            YWInformationBankModel* infoModel = [self informationModelWithSet:set];
            [allInformationArray addObject:infoModel];
        }
        [db closeOpenResultSets];
    }];
    [allInformationArray enumerateObjectsUsingBlock:^(YWInformationBankModel* _Nonnull infoModel, NSUInteger idx, BOOL* _Nonnull stop) {
        infoModel.creator = [self handlerWithUniqueId:infoModel.creatorId];
        NSArray* attachmentArr = [self attachmentWithRecordId:infoModel.infoId andType:(YWattachmentType)infoModel.typeId];
        infoModel.attachment = attachmentArr.count ? attachmentArr[0] : nil;
    }];
    return allInformationArray;
}

- (YWInformationBankModel*)informationModelWithSet:(FMResultSet*)set
{
    YWInformationBankModel* infoModel = [[YWInformationBankModel alloc] init];
    infoModel.infoId = [set intForColumn:@"infoId"];
    infoModel.typeId = [set intForColumn:@"typeId"];
    infoModel.name = [set stringForColumn:@"name"];
    infoModel.buildingId = [set stringForColumn:@"buildingId"];
    infoModel.createTime = [set longLongIntForColumn:@"createTime"];
    infoModel.creatorId = [set intForColumn:@"creatorId"];
    infoModel.attachmentId = [set intForColumn:@"attachmentId"];
    return infoModel;
}


#pragma mark - locationRecordsView
/**
 *  名称	巡查巡更记录视图 locationRecordsView
 */
- (BOOL)createKeepWatchAndInspectRecordsView
{
    NSString* dropSql = @"DROP VIEW IF EXISTS locationRecordsView";
    BOOL success = [_fmdb executeUpdate:dropSql];
    if (success) {
        NSString* sql = @"CREATE VIEW IF NOT EXISTS 'locationRecordsView' AS Select locationId,uniqueTag,executeTime,type FROM (SELECT locationId,uniqueTag,patrolTime AS executeTime,1 AS type FROM 'patrolpoint_record' union SELECT locationId,uniqueTag,finishTime AS executeTime,2 AS type FROM 'inspectionEquipment_record' WHERE recordType=1) ";
        return [_fmdb executeUpdate:sql];
    }
    return YES;
}

- (NSArray*)keepWatchAndInspectRecordsWithLocationId:(NSInteger)locationId andPage:(NSInteger)page
{
    __block NSMutableArray* recordsViewArray = [NSMutableArray array];
    __block NSInteger showChount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'locationRecordsView' WHERE locationId=? ORDER BY executeTime DESC LIMIT ?;";
        FMResultSet* set = [db executeQuery:sql, @(locationId), @(showChount)];
        
        while ([set next]) {
            YWLocationRecordsViewModel* recordViewModel = [[YWLocationRecordsViewModel alloc] init];
            recordViewModel.executeTime = [set longLongIntForColumn:@"executeTime"];
            recordViewModel.locationId = [set intForColumn:@"locationId"];
            recordViewModel.uniqueTag = [set stringForColumn:@"uniqueTag"];
            recordViewModel.type = [set intForColumn:@"type"];
            [recordsViewArray addObject:recordViewModel];
        }
        [db closeOpenResultSets];
    }];
    if (recordsViewArray.count > 0) {
        __block NSMutableArray* allRecords = [NSMutableArray array];
        [self.dbQeue inDatabase:^(FMDatabase* db) {
            [recordsViewArray enumerateObjectsUsingBlock:^(YWLocationRecordsViewModel* _Nonnull recordViewModel, NSUInteger idx, BOOL* _Nonnull stop) {
                NSString* sql = nil;
                FMResultSet* set = nil;
                if (recordViewModel.type == 1) {
                    sql = @"SELECT  * FROM 'patrolpoint_record' WHERE uniqueTag=? AND locationId = ? ";
                }
                else if (recordViewModel.type == 2){
                    sql = @"SELECT  * FROM 'inspectionEquipment_record' WHERE uniqueTag=? AND locationId = ? ";
                }
                set = [db executeQuery:sql, recordViewModel.uniqueTag, @(recordViewModel.locationId)];
                while ([set next]) {
                    if (recordViewModel.type == 1) {
                        YWPatrolPointRecord *pointRecord = [[YWKeepWatchDBManager shareManager] patrolPointRecordWithFMResultSet:set FMDatabase:db];
                        NSString *dayMonthString = [YWCommonTool showTime:pointRecord.patrolTime / 1000 andFormatter:KTimeFormatWithOutDayMonth];
                        pointRecord.dayMonthString = dayMonthString;
                        [allRecords addObject:pointRecord];
                    }
                    else {
                        YWInspectionEquipmentRecord* record = [[YWInspectionMissionDBManager shareManager] inspectionEquipmentRecordWithFMResultSet:set FMDatabase:db];
                        [allRecords addObject:record];
                    }
                }
            }];
            [db closeOpenResultSets];
        }];
        return allRecords;
    }
    return nil;
}

- (NSArray*)keepWatchAndInspectRecordsInLedgerLocationDetailWithLocationId:(NSInteger)locationId andPage:(NSInteger)page type:(NSInteger)type{
    __block NSInteger showChount = page * 10;
    __block NSMutableArray* allRecords = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = nil;
        FMResultSet* set = nil;
        if (type == YWKeepWatchOrInspectionTypeKeepWatch) {
            sql = @"SELECT  * FROM 'patrolpoint_record' WHERE locationId = ? ORDER BY patrolTime DESC LIMIT ?";
        }
        else if (type == YWKeepWatchOrInspectionTypeInspection){
            sql = @"SELECT  * FROM 'inspectionEquipment_record' WHERE locationId = ? ORDER BY finishTime DESC LIMIT ?";
        }
        set = [db executeQuery:sql, @(locationId), @(showChount)];
        
        //按照时间排序后，分时间段显示，构建二维数组
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            if (type == YWKeepWatchOrInspectionTypeKeepWatch) {
                YWPatrolPointRecord *pointRecord = [[YWKeepWatchDBManager shareManager] patrolPointRecordWithFMResultSet:set FMDatabase:db];
                NSString *timeDate = [YWCommonTool showChineseFormatterDate:pointRecord.patrolTime/1000];
                if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                    lastDate = timeDate;
                    array = [NSMutableArray array];
                }
                [array addObject:pointRecord];
                if (![allRecords containsObject:array] && array.count) {
                    [allRecords addObject:array];
                }
            }
            else {
                YWInspectionEquipmentRecord* record = [[YWInspectionMissionDBManager shareManager] inspectionEquipmentRecordWithFMResultSet:set FMDatabase:db];
                NSString *timeDate = [YWCommonTool showChineseFormatterDate:record.executeTime/1000];
                if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                    lastDate = timeDate;
                    array = [NSMutableArray array];
                }
                [array addObject:record];
                if (![allRecords containsObject:array] && array.count) {
                    [allRecords addObject:array];
                }
            }
        }
        [db closeOpenResultSets];
    }];
    return allRecords.count ? allRecords : nil;
}

- (NSArray *)patrolRecordsWithEquipmentId:(NSString*)equipmentId andPage:(NSInteger)page{
    __block NSMutableArray* patrolRecordsArray = [NSMutableArray array];
    __block NSInteger showChount = page * 10;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'inspectionEquipment_record' WHERE equipmentId=? ORDER BY finishTime DESC LIMIT ?;";
        FMResultSet* set = [db executeQuery:sql, equipmentId,@(showChount)];
        
        NSString *lastDate = nil;
        NSMutableArray *array = nil;
        while ([set next]) {
            YWInspectionEquipmentRecord* record = [[YWInspectionMissionDBManager shareManager] inspectionEquipmentRecordWithFMResultSet:set FMDatabase:db];
            NSString *timeDate = [YWCommonTool showChineseFormatterDate:record.executeTime/1000];
            if (lastDate==nil || ![timeDate isEqualToString:lastDate]) {
                lastDate = timeDate;
                array = [NSMutableArray array];
            }
            [array addObject:record];
            if (![patrolRecordsArray containsObject:array] && array.count) {
                [patrolRecordsArray addObject:array];
            }
        }
        [db closeOpenResultSets];
    }];
    return patrolRecordsArray.count ? patrolRecordsArray : nil;
}

#pragma mark - 巡查,巡更记录和报障关联表
- (BOOL)createRecordAndPostTroubleRelTable{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'record_PostTrouble_Rel' (troubleId integer,detailUniqueTag varchar) ";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)isExistRelWithTroubleId:(NSInteger)troubleId detailUniqueTag:(NSString*)detailUniqueTag
{
    __block BOOL ret = NO;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* selectSQL = @"SELECT * FROM record_PostTrouble_Rel WHERE troubleId=? AND detailUniqueTag=?;";
        FMResultSet* set = [db executeQuery:selectSQL,@(troubleId),detailUniqueTag];
        if ([set next]) {
            ret = YES;
        }
        [db closeOpenResultSets];
    }];
    return ret;
}

- (void)saveRecordAndPostTroubleRelWithtroubleId:(NSInteger)troubleId detailUniqueTag:(NSString*)detailUniqueTag{
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'record_PostTrouble_Rel' WHERE troubleId=? AND detailUniqueTag=?;";
        FMResultSet* set = [db executeQuery:sql, @(troubleId),detailUniqueTag];
        if (![set next]) {
            sql = @"INSERT INTO 'record_PostTrouble_Rel' (troubleId, detailUniqueTag) VALUES (?, ?);";
            [db executeUpdate:sql, @(troubleId),detailUniqueTag];
        }
        [db closeOpenResultSets];
    }];
}

- (void)updateRecordAndPostTroubleRelTableUniqueTag:(NSString*)uniqueTag newTroubleId:(NSInteger)newTroubleId{
    __block NSInteger oldTroubleId = 0;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT troubleId FROM 'YW_ReportTrouble' WHERE uniqueTag = ?;";
        FMResultSet* set = [db executeQuery:sql, uniqueTag];
        if ([set next]) {
            oldTroubleId = [set longForColumn:@"troubleId"];
        }
        if (oldTroubleId) {
            sql = @"UPDATE 'record_PostTrouble_Rel' SET troubleId=? WHERE troubleId=?;";
            [db executeUpdate:sql, @(newTroubleId), @(oldTroubleId)];
        }
        [db closeOpenResultSets];
    }];
}

- (NSArray *)troubleIdArrayWithDetailUniqueTag:(NSString *)detailUniqueTag{
    __block NSMutableArray* troubleIdArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT distinct troubleId FROM 'record_PostTrouble_Rel' WHERE detailUniqueTag = ?;";
        FMResultSet* set = [db executeQuery:sql,detailUniqueTag];
        while ([set next]) {
            long troubleID = [set longForColumn:@"troubleId"];
            if (troubleID>0) {
                NSString *troubleId = [NSString stringWithFormat:@"%ld",troubleID];
                [troubleIdArray addObject:troubleId];
            }
        }
        [db closeOpenResultSets];
    }];
    return troubleIdArray;
}

- (NSArray *)postTroubleArrayWithDetailUniqueTag:(NSString *)detailUniqueTag{
    __block NSMutableArray* reportTroubleArray = [NSMutableArray array];
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'YW_ReportTrouble' WHERE troubleId IN ( SELECT distinct troubleId FROM 'record_PostTrouble_Rel' WHERE detailUniqueTag = ? );";
        FMResultSet* set = [db executeQuery:sql,detailUniqueTag];
        while ([set next]) {
            YWReportTroubleModel* reportTrouble = [[YWReportTroubleDBManager shareManager] reportTroubleWithFMResultSet:set FMDatabase:db needSelectTroubleMission:YES];
            [reportTroubleArray addObject:reportTrouble];
        }
        [db closeOpenResultSets];
    }];
    return reportTroubleArray;
}


#pragma mark - 设备的使用方法
- (BOOL)createEquipmentUseMenthodTable{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'equipment_useMenthod' (methodId integer NOT NULL UNIQUE,content varchar,createTime timestamp,updateTime timestamp,status smallint,organizationNo varchar,equipmentTypeId integer) ";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)updateEquipmentUseMenthodWithArray:(NSArray*)useMenthodArray{
    __block BOOL executeResult = YES;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [useMenthodArray enumerateObjectsUsingBlock:^(YWEquipmentUseMenthod* _Nonnull useMethod, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString* sql = @"SELECT * FROM 'equipment_useMenthod' WHERE methodId=?";
            FMResultSet* set = [db executeQuery:sql, @(useMethod.methodId)];
            if ([set next]) {
                sql = @"UPDATE 'equipment_useMenthod' SET content =?,createTime=?,updateTime =?,status =?,organizationNo=?,equipmentTypeId=? WHERE methodId=?";
                executeResult = [db executeUpdate:sql, useMethod.content,@(useMethod.createTime),@(useMethod.updateTime),@(useMethod.status),useMethod.organization.organizationNo,@(useMethod.equipmentType.equipmentTypeId),@(useMethod.methodId)];
            }else {
                sql = @"INSERT INTO 'equipment_useMenthod' (methodId,content,createTime,updateTime,status,organizationNo,equipmentTypeId) VALUES (?,?,?,?,?,?,?)";
                executeResult = [db executeUpdate:sql, @(useMethod.methodId),useMethod.content,@(useMethod.createTime),@(useMethod.updateTime),@(useMethod.status),useMethod.organization.organizationNo,@(useMethod.equipmentType.equipmentTypeId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSTimeInterval)useMenthodMaxUpdateTime{
    __block NSTimeInterval updateTime = 0 ;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT MAX(updateTime) AS maxUpdateTime FROM 'equipment_useMenthod'";
        FMResultSet* set = [db executeQuery:sql];
        if ([set next]) {
            updateTime = [set longLongIntForColumn:@"maxUpdateTime"];
        }
        [db closeOpenResultSets];
    }];
    return updateTime;
}

- (YWEquipmentUseMenthod*)useMenthodWithEquipmentTypeId:(NSInteger)equipmentTypeId{
    __block YWEquipmentUseMenthod* useMenthod = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_useMenthod' WHERE equipmentTypeId=? AND status=0";
        FMResultSet* set = [db executeQuery:sql, @(equipmentTypeId)];
        while ([set next]) {
            useMenthod = [self useMethodWithSet:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return useMenthod;
}

- (YWEquipmentUseMenthod*)useMethodWithSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWEquipmentUseMenthod* useMenthod = [[YWEquipmentUseMenthod alloc] init];
    useMenthod.methodId = [set intForColumn:@"methodId"];
    useMenthod.content = [set stringForColumn:@"content"];
    useMenthod.createTime = [set longLongIntForColumn:@"createTime"];
    useMenthod.updateTime = [set longLongIntForColumn:@"updateTime"];
    useMenthod.status = [set intForColumn:@"status"];
    //useMenthod.organization
    //useMenthod.equipmentType
    return useMenthod;
}

#pragma mark - 设备的使用范围
- (BOOL)createEquipmentUseRangeTable{
    NSString* sql = @"CREATE TABLE IF NOT EXISTS 'equipment_useRange' (rangeId integer NOT NULL UNIQUE,content varchar,createTime timestamp,updateTime timestamp,status smallint,organizationNo varchar,equipmentTypeId integer) ";
    return [_fmdb executeUpdate:sql];
}

- (BOOL)updateEquipmentUseRangeWithArray:(NSArray*)useRangeArray{
    __block BOOL executeResult = YES;
    [self.dbQeue inTransaction:^(FMDatabase* db, BOOL* rollback) {
        [useRangeArray enumerateObjectsUsingBlock:^(YWEquipmentUseRange* _Nonnull useRange, NSUInteger idx, BOOL* _Nonnull stop) {
            NSString* sql = @"SELECT * FROM 'equipment_useRange' WHERE rangeId=?";
            FMResultSet* set = [db executeQuery:sql, @(useRange.rangeId)];
            if ([set next]) {
                sql = @"UPDATE 'equipment_useRange' SET content =?,createTime=?,updateTime =?,status =?,organizationNo=?,equipmentTypeId=? WHERE rangeId=?";
                executeResult = [db executeUpdate:sql, useRange.content,@(useRange.createTime),@(useRange.updateTime),@(useRange.status),useRange.organization.organizationNo,@(useRange.equipmentType.equipmentTypeId),@(useRange.rangeId)];
            }else {
                sql = @"INSERT INTO 'equipment_useRange' (rangeId,content,createTime,updateTime,status,organizationNo,equipmentTypeId) VALUES (?,?,?,?,?,?,?)";
                executeResult = [db executeUpdate:sql, @(useRange.rangeId),useRange.content,@(useRange.createTime),@(useRange.updateTime),@(useRange.status),useRange.organization.organizationNo,@(useRange.equipmentType.equipmentTypeId)];
            }
            if (!executeResult) {
                *stop = YES;
                *rollback = YES;
            };
        }];
        [db closeOpenResultSets];
    }];
    return executeResult;
}

- (NSTimeInterval)useRangeMaxUpdateTime{
    __block NSTimeInterval updateTime = 0 ;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT MAX(updateTime) AS maxUpdateTime FROM 'equipment_useRange'";
        FMResultSet* set = [db executeQuery:sql];
        if ([set next]) {
            updateTime = [set longLongIntForColumn:@"maxUpdateTime"];
        }
        [db closeOpenResultSets];
    }];
    return updateTime;
}

- (YWEquipmentUseRange*)useRangeWithEquipmentTypeId:(NSInteger)equipmentTypeId{
    __block YWEquipmentUseRange* useRange = nil;
    [self.dbQeue inDatabase:^(FMDatabase* db) {
        NSString* sql = @"SELECT * FROM 'equipment_useRange' WHERE equipmentTypeId=? AND status=0";
        FMResultSet* set = [db executeQuery:sql, @(equipmentTypeId)];
        while ([set next]) {
            useRange = [self useRangeWithSet:set FMDatabase:db];
        }
        [db closeOpenResultSets];
    }];
    return useRange;
}

- (YWEquipmentUseRange*)useRangeWithSet:(FMResultSet*)set FMDatabase:(FMDatabase*)db
{
    YWEquipmentUseRange* useRange = [[YWEquipmentUseRange alloc] init];
    useRange.rangeId = [set intForColumn:@"rangeId"];
    useRange.content = [set stringForColumn:@"content"];
    useRange.createTime = [set longLongIntForColumn:@"createTime"];
    useRange.updateTime = [set longLongIntForColumn:@"updateTime"];
    useRange.status = [set intForColumn:@"status"];
    //useMenthod.organization
    //useMenthod.equipmentType
    return useRange;
}
@end
